Nearby lessons

13 of 34

Servlet - ServletContext

📌 What You Will Learn
  • Understand UNIT-3: The Web Container Model
  • Understand Demo Program for Servlet Context Parameters
  • Understand ServletConfig
  • Understand ServletContext
  • See complete working code examples

ServletContext is an essential part of the Java Servlet technology. This lesson explains UNIT-3: The Web Container Model, Demo Program for Servlet Context Parameters and InitializeParameterDemoServlet.java with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid.

UNIT-3: The Web Container Model

  • ServletContext
  • Servlet Scopes and Attributes
  • RequestDispatcher
  • Filters
  • Wrappers
  • ServletContext:

Objective: For the servlet context parameters

  • Write Servlet code to access parameters
  • Create Deployment Descriptor elements for the initialization parameters

For every servlet web container will create one ServletConfig object to hold servlet level

configuration information. By using this config object servlet can get its configuration information

like logical name of servlet, initialization parameters etc

Similarly for every web application , web container creates one ServletContext object to maintain

application level configuration information.By using ServletContext object, servlet can get

application level configuration information like context parameters,RequestDispatcher etc..

ServletConfig is per Servlet where as ServletContext is per web application

If initialization parameters are common for several servlets then it is not recommended to declare

those parameters at servlet level.We have to declare those parameters at application level by

using <context-param> tag.

UNIT-3: The Web Container Model

We can declare any number of context parameters but separate <context-param> tag for every

parameter.

<context-param> is the child tag of <web-app> and hence within <web-app> we can declare

anywhere.

Within the servlet we can access context initialization parameters by using ServletContext object.

We can get ServletContext object by using getServletContext() method of ServletConfig interface.

ServletContext context=getServletContext();

(or)

ServletConfig config=getServletConfig();

ServletContext context=config.getServletContext();

ServletContext interface defines the following methods for accessing context initialization

parameters.

public String getInitParameter(String pname)

public Enumeration getInitParameterNames()

Example02
JCode Cell
1 
2<web-app>
3<context-param>
4<param-name>user</param-name>
5<param-value>scott</param-value>
6</context-param>
7...
8</web-app>
9

Demo Program for Servlet Context Parameters

web.xml:

Demo Program for Servlet Context Parameters

Example04
JCode Cell
1 
2<web-app>
3<context-param>
4<param-name>PhoneNumber</param-name>
5<param-value>9292929292</param-value>
6</context-param>
7 
8<context-param>
9<param-name>mailid</param-name>
10<param-value>support@durgasoft.com</param-value>
11</context-param>
12 
13<servlet>
14<servlet-name>DemoServlet</servlet-name>
15<servlet-class>InitializeParameterDemoServlet</servlet-class>
16</servlet>
17 
18<servlet-mapping>
19<servlet-name>DemoServlet</servlet-name>
20<url-pattern>/test</url-pattern>
21</servlet-mapping>
22 
23</web-app>
24

InitializeParameterDemoServlet.java

Note: By default initialization parameter means Servlet Initialization Parameter but not context

initialization parameter.

We can access Servlet Initialization Parameters in the following ways..

String value=getInitParamter("user");

String value=getServletConfig().getInitParamter("user");

We can access Context Initialization Parameters as follows

String value=getServletContext().getInitParameter("user");

String value=getServletConfig().getServletContext().getInitParameter("user");

Comparison between Servlet and Context Initialization Parameters:

PropertiesServlet init-paramContext init-param
1) Deployment DescriptorBy using <init-param> within Servlet
Declaration<Servlet>By using <context-param>

within <web-app>

Example05
JCode Cell
1 
2import javax.servlet.*;
3import javax.servlet.http.*;
4import java.io.*;
5import java.util.*;
6public class InitializeParameterDemoServlet extends HttpServlet
7{
8public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
9{
10PrintWriter out = resp.getWriter();
11out.println("<center><h1>Intialization Parameters</h1></center><hr>");
12ServletContext context = getServletContext();
13Enumeration e =context.getInitParameterNames();
14out.println("<table border=2><tr><th>Parameter Name</th><th>Parameter Value</th></tr>");
15while (e.hasMoreElements())
16{
17String pname = (String)e.nextElement();
18String pvalue = context.getInitParameter(pname);
19out.println("<tr><td>"+pname+"</td><td>"+pvalue+"</td></tr>");
20 
21}
22out.println("</table>");
23out.println("</body></html>");
24}
25}
26

InitializeParameterDemoServlet.java

the Parameters<param-name>
<param-value><context-param>
3) Availability<param-name>
(Scope)</init-param><param-value>

</Servlet>

</context-param>

String value =</web-app>

getInitParameter("pname");

String value =

OR getServletContext().

String value = getServletConfig().getInitParameter("pn");

getInitParameter("pname")

OR

Available only for a particularString value =
Servlet in which <init-param>getServletConfig().
is declaredgetServletContext().

getInitParameter("pname");

Available for all Servlets and

JSP's within the Web Application

Note: whether servlet or context, all initialization parameters are deployment time

constants.From the servlet we can get these values but we cannot set. i.e We have only getter

methods but not setter methods.

Differences between ServletConfig and ServletContext:

Example06
JCode Cell
1 
2Servlet Code to access <init-param> <web-app>
3

ServletConfig

time of Servlet Object Destruction.

Example07
JCode Cell
1 
2For every Sevlet Web Container creates one ServletConfig Object.
3ServletConfig Object will be created at the time of Servlet Object Creation and destroyed at the
4

ServletConfig

ServletConfig config = getServletConfig();

Example08
JCode Cell
1 
2Web Container hand-over Config Object to the Servlet as an Argument to init() Method.
3Within the Servlet we can get its Config Object as follows
4

ServletConfig

provided by Web Server Vendor.

Example09
JCode Cell
1 
2It is not Object of javax.servlet.ServletConfig(I). It is the Object of its Implementation Class
3

ServletConfig

Servlet, Initialization Parameters etc.. by using the following Methods.

getServetName()

getInitParameter()

getInitParameterNames()

getServletContext()

Example10
JCode Cell
1 
2By using Config Object, Servlet can get its Configuration Information like Logical Name of the
3

ServletContext

Application Level Configuration Information.

Example11
JCode Cell
1 
2For every Web Application, Web Container creates one ServletContext Object to hold
3

ServletContext

of Application Undeployment.

Example12
JCode Cell
1 
2Context Object will be created at the time of Application Deployment and destroyed at the time
3

3) Within the Servlet we can get Context Object as follows

ServletContext context = config.getServletContext();

ServletContext context = getServletContext();

3) Within the Servlet we can get Context Object as follows

provided by Web Server Vendor.

Example14
JCode Cell
1 
2It is not Object of javax.servlet.ServletContext(I). It is the Object of its Implementation Class
3

3) Within the Servlet we can get Context Object as follows

getInitParameter()

getAttribute()

getServletInfo()

getResourcePaths()

getContextPath()

log()

getMajorVersion()

getMinorVersion()

*FAQs:

  • What is the difference between ServletConfig and ServletContext?
  • What is the difference between Servlet Initialization Parameters and Servlet Context

Parameters?

Servlet Scopes and Attributes

Objective:

For the fundamental servlet scopes (request,session,context)

  • Write Servlet Code to add,retrieve and remove attributes?

2.For the given scenario identify proper scope?

3.Identify multi threading issues associated with each scope?

There are 3 Types of Parameters are possible.

  • Form Parameters
  • Servlet Initialization Parameters
  • Context Initialization Parameters

These parameters are read-only. i.e from the servlet we can perform only read operation and we

cannot modify, remove values based on our requirement. Hence Parameters concept is not useful

for sharing data between components of web application.

To resolve this problem we should go for attributes concept.Based on our requirement we can

create a new attribute,we can modify the value and we can remove existing attribute. Hence

attributes concept is best suitable for sharing data between components of web application.

Based on our requirement,we have to store attributes in the proper scope.

There are 3 scopes are possible for the servlets.

  • Request Scope
  • Session Scope
  • Application/Context Scope
  • Request Scope:
  • Request scope is maintained by either ServletRequest object or HttpSerlvetRequest object.
  • Request scope will start at the time of request object creation(i.e just before calling service()

method)and ends at the time of request object destruction(i.e just after completing service()

method)

3.The data stored in request scope is available for all components which are processing that

request.

  • ServletRequest interface defines the following methods for attribute management in the

Request scope

1.public void setAttribute(String name,Object value)

To add an attribute.

If the specified attribute is already available then the old value is replaced with new value.

2.public Object getAttribute(String name)

Returns the value associated with the specified attribute.

If the specified attribute is not available then this method returns null.

Example15
JCode Cell
1 
2On the ServletContext Object we can call the following MethodsgetRequestDispatcher()
3

3) Within the Servlet we can get Context Object as follows

Example:

The most common application area where we can use Request scoped attributes is

RequestDispatcher Mechanism

For every request a separate new request object will be created,which can be accessed by only

current thread.Other threads are not allowed to access request scoped attributes.Hence request

scoped attributes are always thread-safe.

Example16
JCode Cell
1 
2public void removeAttribute(String name)
3public Enumeration getAttributeNames()
4

Session Scope

Session scope is maintained by HttpSession object.

Session Scope will start at the time of Session object creation.

HttpSession session=req.getSession();

Session scope ends at the time of Session object destruction(ie at the time of either logout or

timeout)

session.invalidate();

Session Object Creation

HttpSession session=req.getSession();

session.invalidate();

The information stored in the session scope is available for all the components which are

participating in that session.

HttpSession interface defines the following methods for attribute management in session scope

Session Scope

*Note:

Once session expired, we are not allowed to call these methods otherwise we will get

RuntimeException saying IllegalStateException.

Example: login information should be available for total session. Hence we have to store this

information in the session scope.

within the same session we can send multiple requests simultaneously by opening multiple tabs.

Hence session object can be accessed by mutilple threads simultaneously and hence session

scoped attributes are not Thread Safe.

Example18
JCode Cell
1 
2public void setAttribute(String name,Object value)
3public Object getAttribute(String name)
4public void removeAttribute(String name)
5public Enumeration getAttributeNames()
6

Application Scope

Application scope is maintained by ServletContext object.

This scope will start at the time of context object creation. ie at the time of application

deployment or server startup.

Application scope ends at the time of context object destruction. i.e at the time of application

undeployment or server shutdown.

The data stored in application scope will be available to all the components of web application

irrespective of request and end user.

ServletContext interface defines the following methods for attribute management in the

application scope...

Application Scope

ServletContext object can be accessed simultaneously by multiple threads and hence context

scoped attributes are not thread safe.

Instance and static variables can be accessed by multiple threads simultaneously and hence these

are not thread safe.

For every Thread a separate copy of local variables will be created and hence local variable can be

accessed by only current thread. Hence local variables are Thread Safe.

Table:

Member Is Thread Safe?

Request Scope AttributeYes

Session Scope Attribute No

Context Scope Attribute No

Instance Variables No

Static Variables No

Local VariablesYes

Parameters are key-value pairs where both key and value are String objects. Hence at the time of

retrieval it is not required to perform any typecasting.We can assign directly parameter value to

the String type variable.

Eg:

String user=req.getParameter("user");

String user=getInitParameter("user");

Attributes are also key-value pairs. But keys are String type and values can be any type. Hence at

the time of retrieval compulsory we should perform type casting.

String user=req.getAttribute("user");

CE: incompatible types

found: Object

required: String

String user=(String)req.getAttribute("user");

Q. To access the value of request scoped attribute user,which of the following is valid

way?

1.String user=req.getParameter("user");

2.String user=req.getInitParameter("user");

3.String user=getInitParameter("user");

4.String user=req.getAttribute("user");

5.String user=(String)req.getAttribute("user");

Differences b/w Parameters and Attributes:

ParameterAttribute
1) Parameters are Read Only i.e. within the1) Based on our Requirement we can get and
Servlet we can perform Read Operation but weset the Attributes i.e., these are not Read only
can't modify their Values i.e., we have onlyand we have both getters()'s and setters()'s.

getters()'s but not setters()'s.

Example20
JCode Cell
1 
2public void setAttribute(String name,Object value)
3public Object getAttribute(String name)
4public void removeAttribute(String name)
5public Enumeration getAttributeNames()
6

Application Scope

Key and Value are String Objects only.Keys ---- String
Keys ---- StringValue ---- Object

Values ---- String

Example21
JCode Cell
1 
2Attributes are not Deploy time Constants.
3Parameters are Deployment Time Constants.
4Attributes are Key - Value Pairs where Key is
5Parameters are Key - Value Pairs and both String but Value can be any Type of Object.
6

Application Scope

perform Type casting.

Q1. Demo Program to display hit count(number of requests) of web application?

Example22
JCode Cell
1 
2At the time of retrieval we should perform
3At the time of retreival it is not require to Type casting.
4

Application Scope

Q2. Demo Program to display the number of users login in our application.

Example23
JCode Cell
1 
2import javax.servlet.*;
3import javax.servlet.http.*;
4import java.io.*;
5import javax.servlet.annotation.*;
6@WebServlet("/test")
7public class HitCountDemo extends HttpServlet
8{
9public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
10{
11PrintWriter out = resp.getWriter();
12ServletContext context = getServletContext();
13Integer count = (Integer)context.getAttribute("hitcount");
14if(count == null)
15{
16count = 1;
17}
18else
19{
20count++;
21}
22context.setAttribute("hitcount",count);
23out.println("<h1>The number of requests is:"+count+"</h1>");
24}
25}
26

Application Scope

Q. Demo Program to display number of requests in the current session?

Example24
JCode Cell
1 
2import javax.servlet.*;
3import javax.servlet.http.*;
4import java.io.*;
5import javax.servlet.annotation.*;
6@WebServlet("/test")
7public class UsersCount extends HttpServlet
8{
9public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
10{
11PrintWriter out = resp.getWriter();
12ServletContext context = getServletContext();
13Integer count = (Integer)context.getAttribute("usercount");
14HttpSession session = req.getSession();
15if(session.isNew())
16{
17if(count == null)
18{
19count = 1;
20}
21else
22{
23count++;
24}
25context.setAttribute("usercount",count);
26}
27out.println("<h1>The no of users login into our application :"+count+"</h1>");
28}
29}
30

Application Scope

Q. Write a program to display all attributes information present in application scope?

Example25
JCode Cell
1 
2import javax.servlet.*;
3import javax.servlet.http.*;
4import java.io.*;
5import javax.servlet.annotation.*;
6@WebServlet("/test")
7public class SessionHitCountDemo extends HttpServlet
8{
9public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
10{
11PrintWriter out = resp.getWriter();
12HttpSession session = req.getSession();
13Integer count = (Integer)session.getAttribute("hitcount");
14if(count == null)
15{
16count =1;
17}
18else
19{
20count++;
21}
22session.setAttribute("hitcount",count);
23out.println("<h1>The number of requests in the current session is:"+count+"</h1>");
24}
25}
26

Application Scope

Note: In application scope web container will add some attributes for its internal purpose.

RequestDispatcher

Objective:

  • Describe RequestDispatcher Mechanism?
  • Write Servlet code to create RequestDispatcher?
  • Write Servlet code to forward or include target resource?
  • Identify & Describe attributes added by web container while forwarding and including?

It is not recommended to define total functionality in a single component. It has several serious

disadvantages.

  • Without effecting remaining logic we cannot modify any code. Hence enhancement will become

difficult and maintainability of the application will be down.

  • It does not promote reusability of the code.

Login Page

Validation

Inbox

Mail Compose

Mail Reading

Mail Sending

Error Page

::::::::::::::::

Total Servlet

We can resolve these problems by maintaining a separate component for each task.

Inbox

Login.jsp Validate

Error Page

The main advantages of this approach are

  • Without effecting remaining components we can modify any component. Hence enhancement

will become very easy and improves maintainability of the application.

  • It promotes reusability.

Eg: Where ever validation is required, we can reuse the same ValidateServlet without rewriting.

If total functionality is distributed across multiple components then these components have to

communicate with each other to provide response to end user. We can achieve this

communication by using RequestDispatcher.

Hence the main purpose of RequestDispatcher is to dispatch our request from one component to

another component.

Eg: After validation ValidateServlet has to forward the request to inbox.jsp.For this we can use

RequestDispatcher.

Servlet code for Getting RequestDispatcher:

We can get RequestDispatcher either by using ServletRequest object or by using ServletContext

object.

  • By ServletRequest object:

ServletRequest interface defines the following method for this purpose.

public RequestDispatcher getRequestDispatcher(String targetResouce)

The target Resource can be specified either by absolute path or by relative path.

Eg:

RD rd = req.getRequestDispatcher("/test2");

RD rd = req.getRequestDispatcher("test2");

If the target resouce is not available then we will get 404 status code saying requested resource is

not available.

Example26
JCode Cell
1 
2import javax.servlet.*;
3import javax.servlet.http.*;
4import java.io.*;
5import java.util.*;
6import javax.servlet.annotation.*;
7@WebServlet("/test")
8public class ContextAttributeDemo extends HttpServlet
9{
10public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
11{
12PrintWriter out = resp.getWriter();
13out.println("<h1>Context Attributes</h1>");
14ServletContext context=getServletContext();
15context.setAttribute("durga","SCWCD");
16Enumeration e = context.getAttributeNames();
17 
18while(e.hasMoreElements())
19{
20String name= (String)e.nextElement();
21Object value = context.getAttribute(name);
22out.println(name+"....."+value+"<br>");
23}
24}
25}
26

By ServletContext Object

ServletContext interface defines the following methods for getting RequestDispatcher.

By ServletContext Object

The target Resource should be specified by only absolute path. If we are using relative path(i.e the

path not starts with "/" )then we will get Runtime Exception saying IllegalArgumentException.

Eg:

RD rd = context.getRequestDispatcher("test2"); → RE:IAE

RD rd = context.getRequestDispatcher("/test2");

If the target resource is not available then we will get 404 status code saying requested resource is

not available.

Example28
JCode Cell
1 
2public RequestDispatcher getRequestDispatcher(String targetResource)
3

By ServletContext Object

The argument represents the value associated with the <servlet-name> tag in web.xml. i.e it

represents logical name of the servlet.

If url-pattern is not available then we can use this method.

If the specified servlet is not available then we will get null. On that null if we are trying to call any

method then we will get NullPointerException.

Eg:

RD rd = context.getNamedDispatcher("FirstServlet");

Difference b/w getting RequestDispatcher by ServletRequest and by ServletContext:

RD From Request ObjectRD From Context Object
Example29
JCode Cell
1 
2public RequestDispatcher getNamedDispatcher(String servletName)
3

By ServletContext Object

not based on Servlet Name.1) We can get RD based on either URL Pattern
2) RD rd = req.getRD("/test2");OR based on Servlet Name.
RD rd = req.getRD("test2");2) RD rd = context.getRD("/test2");
We can use either Relative Path OR AbsoluteRD rd = context.getRD("test2");

Path

We should use only Absolute Path but not

Example30
JCode Cell
1 
2We can get RD only based on URL Pattern but
3

By ServletContext Object

within the Web Application i.e., Cross ContextIlleagalArgumentException

Communication is not possible.

Example31
JCode Cell
1 
2By using this RD, we can communicate only Relative Path, otherwise we will get
3

By ServletContext Object

within the Web Application OR outside of the

Web Application i.e., Cross Context

Communication is possible.

Methods of RequestDispatcher:

Once we got RD, we can call the following 2 methods on this object.

Example32
JCode Cell
1 
2By using this RD, we can communicate either
3

By ServletContext Object

Example33
JCode Cell
1 
2public void forward(SR req,SR resp)throws SE,IOE
3public void include(SR req,SR resp)throws SE,IOE
4
📝 Key Takeaways
  • Key ideas of Servlet - ServletContext explained simply
  • Ready-to-use code examples
  • Exam-style questions at the end

🧠 Test Your Knowledge

3 Questions
Progress: 0 / 3