This J2EE example demonstrates a Java Servlet that retrieves some initialization parameters through getInitParameter() method. This method returns the value of the named init parameter or null if it does not exist. The return value is always a single String. It is up to the java servlet to interpret the value. This helps the developer to pass values dynamically instead of hard coding the values, which would then require recompiling.

import javax.servlet.*;
import javax.servlet.http.*;

public class ServletInitParameters extends HttpServlet {
  private String Hello;

  public void init(ServletConfig configthrows ServletException {
  Hello = getInitParameter("greeting");

  Initialization information is passed to the servlet via 
  the ServletConfig parameter of the init() method. 

  public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

  PrintWriter out = response.getWriter();

  out.println("<title>" + Hello + "</title>");
  out.println("<h1>" + Hello + "</h1>");
  public void destroy()
    // nothing to do

Parent Category: Java EE Tips