Difference between ServletConfig and ServletContext


Both ServletConfig and ServletContext are configuration objects used by servlet container to initialize various init parameters for a web application. However they differ in terms of the scope and availability of init parameters defined by both of them.

Init Parameters in deployment descriptor (web.xml)

Init parameters for ServletConfig are defined within <servlet> element for each specific servlet.
<servlet>
 <servlet-name>BeerParamTests</servlet-name>
 <servlet-class>TestInitParams</servlet-class>
 <init-param>
  <param-name>foo</param-name>
  <param-value>bar</param-value>
 </init-param>
 <!-- other stuff -->
</servlet>
Init parameters for ServletContext are defined within the <web-app> element but NOT within a specific <servlet> element.
<web-app>
 <context-param>
  <param-name>foo</param-name>
  <param-value>bar</param-value>
 </context-param>
 <!-- other stuff including servlet declarations -->
</web-app>
Servlet Code

getServletConfig().getInitParameter("foo"); for ServletConfig
getServletContext().getInitParameter("foo"); for ServletContext

Availability

There's only one ServletContext for an entire web app, and all the parts of the web app share it. Hence parameters required by all the servlets should be configured within ServletContext. For example database connection parameters.

But each servlet in the app has its own ServletConfig. Hence the parameters, needed by a particular servlet but should not be accessed by other servlets, should be configured by ServletConfig.

The Container makes a ServletContext when a web app is deployed, and makes the context available to each Servlet and JSP (which becomes a servlet) in the web app.

No comments:

Post a Comment