Nearby lessons
13 of 34Servlet - ServletContext
- 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()
Demo Program for Servlet Context Parameters
web.xml:
Demo Program for Servlet Context Parameters
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:
| Properties | Servlet init-param | Context init-param |
|---|---|---|
| 1) Deployment Descriptor | By using <init-param> within Servlet | |
| Declaration | <Servlet> | By using <context-param> |
within <web-app>
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 particular | String value = |
|---|---|
| Servlet in which <init-param> | getServletConfig(). |
| is declared | getServletContext(). |
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:
ServletConfig
time of Servlet Object Destruction.
ServletConfig
ServletConfig config = getServletConfig();
ServletConfig
provided by Web Server Vendor.
ServletConfig
Servlet, Initialization Parameters etc.. by using the following Methods.
getServetName()
getInitParameter()
getInitParameterNames()
getServletContext()
ServletContext
Application Level Configuration Information.
ServletContext
of Application Undeployment.
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.
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.
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.
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.
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 Attribute | Yes |
|---|
Session Scope Attribute No
Context Scope Attribute No
Instance Variables No
Static Variables No
| Local Variables | Yes |
|---|
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:
| Parameter | Attribute |
|---|---|
| 1) Parameters are Read Only i.e. within the | 1) Based on our Requirement we can get and |
| Servlet we can perform Read Operation but we | set the Attributes i.e., these are not Read only |
| can't modify their Values i.e., we have only | and we have both getters()'s and setters()'s. |
getters()'s but not setters()'s.
Application Scope
| Key and Value are String Objects only. | Keys ---- String |
|---|---|
| Keys ---- String | Value ---- Object |
Values ---- String
Application Scope
perform Type casting.
Q1. Demo Program to display hit count(number of requests) of web application?
Application Scope
Q2. Demo Program to display the number of users login in our application.
Application Scope
Q. Demo Program to display number of requests in the current session?
Application Scope
Q. Write a program to display all attributes information present in application scope?
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.
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.
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 Object | RD From Context Object |
|---|
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 Absolute | RD rd = context.getRD("test2"); |
Path
We should use only Absolute Path but not
By ServletContext Object
| within the Web Application i.e., Cross Context | IlleagalArgumentException |
|---|
Communication is not possible.
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.
By ServletContext Object
- Key ideas of Servlet - ServletContext explained simply
- Ready-to-use code examples
- Exam-style questions at the end