1. ServletConfig & ServletContext :-
ß Suppose let us here we have multiple servlet. Here there are three servlet A, B, C
under classes’ folder. If you want to give any input to all the servlet A, B, C
servlet.
ß I want to pass the same connection object to AServlet , BServlet, CServlet.
Suppose I have a JDBC connection object, I want to give that object to AServlet,
BServlet, CServlet.
ß I have only one resource I want to share that resource to all servlet then what
should will do- it makes as.
ASHUTOSH TRIVEDI
Email:trivedi.ashutosh2013@gmail.com
MNO—9580074408
Read ServletConfig & ServletContext by ASHUTOSH
2. ß I have a single resource if I want to share same resource to all the user then
resource need to become to public resource.
ß An object of ServletContext is created by the web container at time of deploying
the project.
ß This object can be used to get configuration information from web.xml file.
ß There is only one ServletContext object per web application.
ß It is one per web application. So it is called as the global memory of web
application.
ß ServletContext object means it is the object of a java class (container supplier)
implementing javax.servlet.ServletConext interface.
ß Servlet container creates this object either during deployment of the web
application or during server start-up.
ß Servlet container destroys this object automatically when web application is
undeployed or reloaded or stopped or when server is stopped/ re-started.
¸ An object of ServletContext is created by the web container at the time of deploying
the project.
¸ There is only one ServletContext object per web application.
¸ This Servletcontext object can be used to get configuration information from
web.xml file. If any information is shared to many object, it is better to provide it
from the web.xml file using the <context-param> element.
3. ¸ Easy to maintain if any information is shared to all the servlet it is better to make it
available for all the servlet. We provide this information from the web.xml, so if the
information is changer we don't need to modify the servlet. Thus if removes
maintenance problem.
¸ Every web Application runs in a separate context which isolates it from another
application running in the same server.
¸ Defines a set of methods that a servlet uses to communicate with its servlet container,
for example to get the MIME type of a file dispatch requests or write to a log file.
4. ¸ For every Servlet, web container will create one ServletConfig object to maintain
Servlet level initialization parameter. By using this object Servlet can get its
configuration information.
¸ Similarly for every web-application webcontainer creates one ServletContext object
to maintain application level configuration information.
¸ Servlet can get application level configuration information through this context
object only.
¸ ServletConfig per Servlet, whereas ServletContext per Web-application.
¸ If initialization parameters are common for all Servlets then it is not recommended to
declare those parameters at Servlet level , we have to declare such type of parameters
at application -level by using < context-param >
<web-app>
<context-param>
<param-name>username</param-name>
<param-value>scott</param-value>
</context-param>
</web-app>
¸ We can declare any number of context parameters but one < context-param > for each
Servlet.
¸ < context-param > is the direct child tag of <web-app > & hence we can declare
anywhere within <web-app>
¸ The context initialization parameters are available throughout the web-application
anywhere.
¸ If we want to use same init-parameters then we can declare at context-level as
<context-param>
<param-name>username</param-name>
<param-value>scott</param-value>
</context-param>
5. ¸ Within the Servlet we can access these context initialization parameters by using
ServletContext object.
How to Get ServletContext Object into Our Servlet Class
∑ In servlet programming we have 3 approaches for obtaining an object of
ServletContext interface.
Way 1.
Syntax-
//We can get ServletContext object from ServletConfig
ServletConfig conf = getServletConfig();
ServletContext context = conf.getServletContext();
∑ First obtain an object of ServletConfig interface ServletConfig interface contain
direct method to get Context object, getServletContext();.
Way 2.
∑ Direct approach, just call getServletContext() method available in GenericServlet
[pre-defined]. In general we are extending our class with HttpServlet, but we know
HttpServlet is the sub class of GenericServlet.
Syntax-
//Another convenient way to get ServletContext object
ServletContext context = getServletContext();
Way 3.
∑ We can get the object of ServletContext by making use of HttpServletRequest
object, we have direct method in HttpServletRequest interface.
Syntax:-
public class MyJava extends HttpServlet
{
public void doGet/doPost(HttpServletRequest req,-)
{
ServletContext ctx = req.getServletContext();
}
}
6. Commonly used methods of ServletContext interface
There is given some commonly used methods of ServletContext interface.
1. public String getInitParameter(String name):Returns the parameter value for the
specified parameter name.
2. public Enumeration getInitParameterNames():Returns the names of the context's
initialization parameters.
3. public void setAttribute(String name,Object object):sets the given object in the
application scope.
4. public Object getAttribute(String name):Returns the attribute for the specified
name.
5. public Enumeration getInitParameterNames():Returns the names of the context's
initialization parameters as an Enumeration of String objects.
6. public void removeAttribute(String name):Removes the attribute with the given
name from the servlet context.
Syntax to provide the initialization parameter in Context scope
∑ The context-param element, subelement of web-app, is used to define the initialization
parameter in the application scope. The param-name and param-value are the sub-
elements of the context-param. The param-name element defines parameter name and
and param-value defines its value.
web.xml
<web-app>
....
<context-param>
<param-name>parametername</param-name>
<param-value>parametervalue</param-value>
</context-param>
...
</web-app>
7. Example of ServletContext to get the initialization parameter
∑ In this example, we are getting the initialization parameter from the web.xml file and
printing the value of the initialization parameter. Notice that the object of ServletContext
represents the application scope. So if we change the value of the parameter from the
web.xml file, all the servlet classes will get the changed value. So we don't need to
modify the servlet. So it is better to have the common information for most of the
servlets in the web.xml file by context-param element. Let's see the simple example:
web.xml
<web-app>
....
<display-name> HelloGenericServlet </display-name>
<description>
This is a simple web application with a source code .
</description>
<context-param>
<param-name>drivername</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</context-param>
<context-param>
<param-name>username</param-name>
<param-value>system</param-value>
</context-param>
<context-param>
<param-name>password</param-name>
<param-value>oracle</param-value>
</context-param>
<servlet>
<servlet-name> context </servlet-name>
<servlet-class> ServletContextDemoServlet </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> context</servlet-name>
<url-pattern> /context </url-pattern>
</servlet-mapping>
...
8. import java.io.*;
import javax.servlet.*;
public class ServletContextDemoServlet implements HttpServlet{
private static final long serialVersionUID=11;
ServletConfig config=null;
public void init() throws ServletException
{
System.out.println("-----------------------------------------------------------------");
System.out.println("init method is called in "+ this.getClass().getName());
System.out.println("-----------------------------------------------------------------");
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws IOException,ServletException{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
ServletContext context=getServletContext();
out.print("<b> Read specific InitParam using context.getInitParameter(String paramName
</b> <br> <br>");
String driverName=context.getInitParameter("drivername");
out.print(driverName+"<br><br>")
out.print("<b> Read All InitParameters using getInitParameterNames() method </b> <br>");
Enumeration<String> initParamNamesEnum=context.getInitParameterNames();
String paramName="";
while (initParamNamesEnum.hasMoreElements())
{
paramName = initParamNamesEnum.nextElement();
paramValue= context.getInitParameter(paramName);
out.print("<br> "+ paramName + ": " + paramValue);
}
System.out.println("-----------------------------------------------------------------");
System.out.println("sevice method has been called ");
System.out.println("-----------------------------------------------------------------");
res.setContentType("text/html");
9. PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello generic servlet</b>");
out.print ("<br>");
out.print("</body></html>");
}
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws IOException,ServletException
{
doGet(request, response)
}
public void destroy()
{
System.out.println("-----------------------------------------------------------------");
System.out.println("destroy method has been called and servlet is destroyed ");
System.out.println("-----------------------------------------------------------------");
}
}
// Index.html
<html>
<head><title>Context test</title>
<body>
<li><a href="context">Context Test</a></li>
</body>
</html>
10. ServletConfig (one per SERVLET):
¸ ServletConfig is an interface which is present in javax.servlet.* package.
¸ The purpose of ServletConfig is to pass some initial parameter values, technical
information (driver name, database name, data source name, etc.) to a servlet.
¸ An object of ServletConfig will be created one per servlet.
¸ An object of ServletConfig will be created by the server at the time of executing
public void init (ServletConfig) method.
¸ An object of ServletConfig cannot be accessed in the default constructor of a Servlet
class.Since, at the time of executing default constructor ServletConfig object does not
exist.
¸ By default ServletConfig object can be accessed with in init () method only but not in
doGet and doPost. In order to use, in the entire servlet preserve the reference of
ServletConfig into another variable and declare this variable into a Servlet class as a
data member of ServletConfig.
11. v When we want to give some global data to a servlet we must obtain an object of
ServletConfig.
v web.xml entries for ServletConfig
<servlet>
………….
<init-param>
<param-name>Name of the parameter</param-name>
<param-value>Value of the parameter</param-value>
</init-param>
………….
</servlet>
For example:
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>serv1</servlet-class>
<init-param>
<param-name>v1</param-name>
<param-value>10</param-value>
</init-param>
<init-param>
<param name>v2</param name>
12. <param-value>20</param-value>
</init-param>
</servlet>
ÿ The data which is available in ServletConfig object is in the form of (key, vlaue)
OBTAINING an object of ServletConfig:
v An object of ServletConfig can be obtained in two ways, they are by calling
getServletConfig() method and by calling init (ServletConfig).
v Within the Servlet we can get its Config object as follows.
ServletConfig config=getServletConfig();
By calling getServletConfig () method:
v getServletConfig() is the method which is available in javax.servlet.Servlet interface.
This method is further inherited and defined into a class called
javax.servlet.GenericServlet and that method is further inherited into another predefined
class called javax.servlet.http.HttpServlet and it can be inherited into our own servlet
class.
For example:
public class serv1 extends HttpServlet
{
public void doGet (HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
…………
…………
ServletConfig config=this.getServletConfig ();
…………
…………
}
}
13. In the above example an object config contains (key, value) pair data of web.xml file which
are written under <init-param> tag of <servlet> tag.
v By calling init (ServletConfig):
For example:
public class serv2 extends HttpServlet
{
ServletConfig sc;
public void init (ServletConfig sc)
{
Super.init (sc); // used for calling init (ServletConfig) method of HttpServlet
this.sc=sc; // ServletConfig object sc is referenced
}
…………
…………
};
RETRIEVING DATA from ServletConfig interface object:
∑ In order to get the data from ServletConfig interface object we must use the following
methods:
public String getInitParameter (String); ____________ 1
public Enumeration getInitParameterNames (); ________ 2
v Method-1 is used for obtaining the parameter value by passing parameter name
Key Value
V1 10
V2 20
V3 30
Parameter-name Parameter-value
14. String val1=config.getInitParameter (“v1”);
String val2=config.getInitParameter (“v2”);
String val3=config.getInitParameter (“v3”);
vMethod-2 is used for obtaining all parameter names and their corresponding parameter
values.
For example:
Enumeration en=config.getInitParameterNames ();
while (en.hasMoreElements ())
{
Object obj=en.nextElement ();
String pname= (String) obj;
String pvalue=config.getInitParameter (pname);
out.println (pvalue+” is the value of ”+pname);
}
Serv1.java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class Serv1 extends HttpServlet
{
public void doGet (HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
res.setContentType ("text/html");
PrintWriter pw=res.getWriter ();
ServletConfig config=getServletConfig ();
String val1=config.getInitParameter ("v1");
String val2=config.getInitParameter ("v2");
String val3=config.getInitParameter ("v3");
String val4=config.getInitParameter ("v4");
pw.println ("<h3> Value of v1 is "+val1+"</h3>");
pw.println ("<h3> Value of v2 is "+val2+"</h3>");
pw.println ("<h3> Value of v3 is "+val3+"</h3>");
pw.println ("<h3> Value of v4 is "+val4+"</h3>");
}
};
15. Serv2.java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class Serv2 extends HttpServlet
{
public void doGet (HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
res.setContentType ("text/html");
PrintWriter pw=res.getWriter ();
ServletConfig config=getServletConfig ();
Enumeration en=config.getInitParameterNames ();
while (en.hasMoreElements ())
{
Object obj=en.nextElement ();
String pname= (String) obj;
String pvalue=config.getInitParameter (pname);
pw.println ("</h2>"+pvalue+" is the value of "+pname+"</h2>");
}
}
}
web.xml:
<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>Serv1</servlet-class>
<init-param>
<param-name>v1</param-name>
<param-value>10</param-value>
</init-param>
<init-param>
<param-name>v2</param-name>
<param-value>20</param-value>
</init-param>
</servlet>
<servlet>
<servlet-name>pqr</servlet-name>
<servlet-class>Serv2</servlet-class>
18. Property Servlet init-param Servlet context-param
1. declaration
By using init-param with in
servlet.
<servlet>
<init-param>
<param-name>
<param-value>
</init-param>
</servlet>
By using init-param with in
web-app.
<servlet>
<context-param>
<param-name>
<param-value>
</context-param>
</servlet>
2. Servlet code to
Access the parameter
String
value=getInitParameter("pname")
;
(or)
String value=getServletConfig(
).getInitParameter("pname");
String
value=getServletContext(
).getInitParameter("pname")
;
(or)
String
value=getServletConfig(
).getServletContext(
).getInitParameter("pname")
;
3. Availability(Scope)
Available only for a particular
Servlet in which <init-param> is
declared.
Available for all Servlet's &
Jsp's within the web-
application.