Sunday, March 23, 2014

The Difference between ServletContext and ServletConfig

The servletContext is used to provide configuration that would be available to all servlets in a web application, while servletConfig is used to provide configuration per servlet level.


Specifying and retrieving servletContext configurations.

To specify servletContext configuration, you do so in your web.xml via the <context-param/> tag. For example:

<context-param>
<param-name>timeout</param-name>
<param-value>60</param-value>
</context-param>

and to retrieve these parameters in any of the defined servlets you have:

String value = getServletContext().getInitParameter("timeout");

Specifying and retrieving servletConfig configurations.

Since servletConfig are available per servlet, the definition is within the servlet definition in the web.xml. This is done using the <init-param/> tag.

<servlet>
    <servlet-name>Polling Servlet</servlet-name>
    <servlet-class>com.foo.pollServlet</servlet-class>
    <init-param>  
        <param-name>timeout</param-name> 
        <param-value>60</param-value> 
    </init-param> 
</servlet>

With this, the specified parameters are only available in the com.foo.pollServlet servlet and can be retrieved by:

String value = getServletConfig().getInitParameter("timeout");

Left to me, I would say the not so intuitive choice of words, used to describe these two configuration type, is the cause of confusion most people usually have. I would rather have had the configurations per servlet level called servletConext while configurations that are on the web app level (that are available to all servlet) called appContext or webappContext.

No comments: