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

 

 S.No.  ServletConfig  ServletContext
 1. one ServletConfig object per servlet  one ServletContext object shared by all the servlets in application and if the web application is distributed, it is one per JVM
 2.  Available only to the servlet in which init-param is configured  Available to any servlet or jsp that is part of the web application
 3.  Accessed by using getServletConfig() Accessed by using getServletContext()
 4.  Use  ServletConfig object to pass deploy-time information to the servlet(a database name)  Use ServletContext object to access web-app parameters
 5.  in web.xml

<servlet>   
<servlet-name>ServletContextTest</servlet-name>   
 <servlet-class>   
  com.example.ServletContextTest
 </servlet-class>   
 <init-param>   
  <param-name>paramName</param-name>  
  <param-value>paramValue</param-value>  
 </init-param>   
</servlet>

 in web.xml

<context-param>   
<param-name>paramName</param-name>   
<param-value>paramValue</param-value>   
</context-param>

 

Rate this post

Leave a Reply