Configure the Behavior of Servlets While They Are Loaded

Servlets can be configured using the initialization parameter. These parameters can be anything like username, password, URL, etc for accessing a database connection, the location of the configuration file, etc.

Assume the servlet is MyServlet.class and the parameter to pass is param1. The following steps show how to use param1, with MyServlet.

  1. Add the following entry in web.xml:
    			MyServlet		MyServlet		MyServlet					param1			It is value of param1			
  2. This servlet code reads the initialization parameters from the ServletConfig class:
    		javax.servlet.ServletConfig config = getServletConfig();		String value1 = config.getInitParameter("param1");

Place this code in the init() method of the servlet so that the parameters are read while the servlet loads and sets global variables for use by the service method each time.

You can pass as many parameters this way with a different element for each param.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: