Saturday, February 25, 2012

web.xml - context & init params

You can specify parameters to your web application in the web.xml, using the tags <context-param> and <init-param>.

The former are "global" - they can be accessed by all servlets.
The later are servlet-specific.

Let us see this with an example.

We will declare a 'color' and a 'size'.

Update your web.xml, like this:
 <web-app>   
<context-param>
<param-name>color</param-name>
<param-value>red</param-value>
</context-param>

<servlet>
<servlet-name>hello1</servlet-name>
<servlet-class>org.confucius.HelloWorld</servlet-class>
<init-param>
<param-name>size</param-name>
<param-value>medium</param-value>
</init-param>
</servlet>

<servlet>
<servlet-name>hello2</servlet-name>
<servlet-class>org.confucius.HelloWorld</servlet-class>
<init-param>
<param-name>size</param-name>
<param-value>large</param-value>
</init-param>
</servlet>

<servlet-mapping>
<servlet-name>hello1</servlet-name>
<url-pattern>/hello1</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>hello2</servlet-name>
<url-pattern>/hello2</url-pattern>
</servlet-mapping>

</web-app>

We have declared two servlets, hello1 and hello2 - both of which point to the same class HelloWorld.
One is configured with a size 'medium, the other with size 'large'.

Let us now write HelloWorld.java (in your /src/org/confucius) which will read these parameters, like this:
 package org.confucius;  

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloWorld extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String color = getServletContext().getInitParameter("color");
String size = getServletConfig().getInitParameter("size");
response.getWriter().println("Color is " + color);
response.getWriter().println("Size is " + size);
}
}

<context-param> is accessed via ServletContext and <init-param> via ServletConfig.

Build HelloWorld.war and deploy it, then point your browser to:
http://localhost:8080/HelloWorld/hello1

You will see the color set to red and the size to medium.

Now point your browser to:
http://localhost:8080/HelloWorld/hello2

You will see the color set to red and the size to large.

Thus, each servlet accesses its own init-param, but they all access the same context-param.

No comments: