RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Advanced
Feb 23, 2005

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:
    			<param-value>It is value of param1</param-value>
  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 <init-param> element for each param.

Amit Tuli
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date