Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Advanced
Feb 22, 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:
    
    	<servlet>
    		<servlet-name>MyServlet</servlet-name>
    		<display-name>MyServlet</display-name>
    		<servlet-class>MyServlet</servlet-class>
    		<init-param>
    			<param-name>param1</param-name>
    			<param-value>It is value of param1</param-value>
    		</init-param>
    	</servlet>
    
  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
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap