Friday, December 16, 2011

Difference between ServletConfig and ServletContext

Following table lists down the main differences and others things are discussed afterwords:
ServletConfigServletContext(It should have been ApplicationContext)
One ServletConfig object is created per servlet One ServletContext object is created per Application
Can be used to pass deployment time information to the Servlet. Information is stored as parameters in the deployment descriptor(web.xml) Can be used to share Application level information across servlets and is this information is also stored in the web.xml as well as parameters (So it kind of acts as GlobalContext or Application Context)
Provides a set of methods to set and get the initialization configuration information Provides a set of methods to the servlet so that servlet can communicate with the Container
------------------------Servlet can access a ServletContext object only through ServletConfig object

Working with ServletConfig:

We will explaing here how to declare the Servlet init Parameters in in the Deployment Descriptor(web.xml) and how to retrieve them in the servlet also how to get the object of Servlet Context from ServletConfig.
web.xml: Declaring init parameters for a specific servlet

    
    SampleServ
    SampleServ
    in.javaespresso.web.SampleServ
    
     Sample Init Parameters
     servParamservValue
  
Servlet Code: Getting init parameters inside the servlet
getServletConfig().getInitParameter("servParam");
Servlet Code: Getting ServletContext object using ServletConfig
ServletContext context = getServletConfig().getServletContext();

Working with ServletContext:

Let us get the context paramteres declared in the web.xml in the servlet and jsp
web.xml: Declaring context parameters

    Sample context parameters
    emailjava.espresso@gmail.com
Servlet Code: Accessing context params in Servlet
getServletContext().getInitParameter("email")
JSP code: Accessing context params in JSP
<%
getServletContext().getInitParameter("email");
%>

Please find the code for the article attached here

2 comments:

  1. good differences between servletconfig and servletcontext. One more point to note about these two is that due to them only servlets don't have constructor as in earlier days dynamically loaded classes didn't have constructors in them.

    ReplyDelete
  2. Nice points you have covered on ServletContext and ServletConfig. Here you can find some more points on ServletConfig and ServletContext.

    ReplyDelete