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


ServletConfig
The parameter scope is limited to the scope of the servlet in which the parameter is defined. For example, shopping cart of a user is specific to a particular user so servletconfig params can be used.
  • One ServletConfig per servlet
  • It is used to pass deploy-time info to servlet and configured in the deployment descriptor file.
  • It is used to access ServletContext
  • It is within the Servlet element in Deployment descriptor.
  • It is accessed by using getServletConfig().getInitParameter("myname");
  • It is available only to the servlet in which init-param is configured.
<servlet> 
<display-name>InitParamTest</display-name> 
<servlet-name>InitParamTest</servlet-name> 
<servlet-class> test.InitParamTest</servlet-class> 
<init-param> 
<description>test parameter</description> 
<param-name>myname</param-name> 
<param-value>DummyValue</param-value> 
</init-param> 
</servlet>   

ServletContext :
The parameter scope is application wide and the parameter can be use to store application session info/ application initialization parameters,etc not specific to a servlet.
  • It returns the current context of a web application running in a particular JVM.
  • If the web application is distributed,it is one per JVM.
  • It is used to access the <context-param> elements configured in deployment descriptor.
  • It is accessed by using getServletContext().getInitParameter("myname");
  • It is available to any servlet or jsp that is part of web application.

 <context-param> 
<param-name>myname</param-name> 
<param-value>DummyValue</param-value> 
</context-param> 



Comments

Popular posts from this blog

Servlet Advantages and Disadvantages

The Deployment Descriptor: web.xml

Session Management