Nearby lessons
30 of 34Servlet - Examples: ServletContext & RequestDispatcher
- See complete runnable servlet programs
- Understand the output of each program
- Copy and deploy programs in Tomcat
ServletContext parameters, attributes, scopes, forward, include, and Foreign RequestDispatcher.
UNIT-3: The Web Container Model
We can declare any number of context parameters but seperate <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
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
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 avaialble 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 seperate 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
*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
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 seperate 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 compulsary 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 seperate 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
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
Demo Program 1 to forward
SecondServlet.java
If we are sending the request to FirstServlet then it will forward request to SecondServlet and
ServletServlet is responsible to provide required response.
Demo Program 2 to forward
ValidateServelt.java
inbox.jsp:
<h1>This is inbox page you can get all mail services</h1>
error.jsp:
<h1>This is error page your credentials are invalid please login again here
<a href="/advapps3D/login.html">LOGIN</a></h1>
Case-1:
Just before forwarding the request,the response object will be cleared automatically by web
container.Hence if any response added by FirstServlet won't be displayed to the end user.
Case-2:
In Forward Mechanism the same request object will be forwarded to the SecondServlet.Hence
information sharing b/w the components is possible in the form of request scoped attributes.
SecondServlet
Note: Tomcat does not implement this feature.In the case of Tomcat, FirstServlet response will be
displayed to the end user.
case-5:
Recursive forward call is always a RuntimeException saying StackOverflowError.
SS
f secondservlet response
SS
Attributes added by web container while forwarding the request:
While forwarding the request from one servlet to another servlet,web container will add some
attributes in the request scope to make original request information available to the Second
Servlet.
SecondServlet will use these attributes to get original request information.
Web container will add the following attributes in request scope.
javax.servlet.forward.request_uri
javax.servlet.forward.context_path
javax.servlet.forward.servlet_path
javax.servlet.forward.path_info
javax.servlet.forward.query_string
FirstServlet.java
ForwardAttributeDemo.java
http://localhost:7777/advapps3F/test1/durga/software?user=durga&pwd=anushka
Output
javax.servlet.forward.request_uri...../advapps3F/test1/durga/software
javax.servlet.forward.context_path...../advapps3F
javax.servlet.forward.servlet_path...../test1
javax.servlet.forward.path_info...../durga/software
javax.servlet.forward.query_string.....user=durga&pwd=anushka
durga.....java
http://localhost:7777/advapps3F/test2
If we are sending the request directly to the ForwardAttributeDemo servlet then we won't get any
attributes.
Note:If we are getting RequestDispatcher by getNamedDispatcher() method then web container
won't add any attributes in the request scope while forwarding the request.
Demo Program for include
SecondServlet.java
If we are sending the request to FirstServlet then the output is:
Hello This is FirstServlet
This is Second Servlet
Hi This is First Servlet again
Attributes added by web container in request scope while performing include call:
javax.servlet.include.request_uri
javax.servlet.include.context_path
javax.servlet.include.servlet_path
javax.servlet.include.path_info
javax.servlet.include.query_string
Note: If we are getting RequestDispatcher by getNamedDispatcher() method then web container
won't add these attributes...
FirstServlet.java (advapps3H)
SecondServlet.java (advapps3I)
http://localhost:7777/advapps3H/test1
Note:
1.RequestDispatcher mechanism will work with in the same server. Hence both applications
should be deployed in the same server.
- Most of the web servers wont provide support for cross context communication due to security
reasons. In this case we will get NullPointerException.
To provide support for cross context communication we have to perform configuration changes at
server level.
In Tomcat we have to add the following in context.xml(Tomcat/conf folder)
<Context crossContext="true">
Note: After commiting the response,we are not allowed to perform sendRedirect() and forward()
calls.Otherwise we will get RE Saying IllegalStateException.
Differences Between forward() and include()
responsible to provide Response.
Differences Between forward() and include()
| only once, mostly as the last Statement. | 3) Within the same Servlet, we can call include() |
|---|
any Number of times and there are no
Differences Between forward() and include()
| Object. It is allowed to change Response Headers | 4) In the case of Include, IncludingServlet (S - 1) |
|---|---|
| also. | having complete Control on the Response Object. |
It is allowed to change Response Headers also.
Differences Between forward() and include()
| allowed to perform Forward, otherwise we will | allowed to perform Include. |
|---|
get
| RE: IlleagalStateException. | 6) Include Mechanism can be used frequently in |
|---|---|
| 6) Forward Mechanism can be used frequently in | JSP's |
Servlets because it is associated with processing. because it is associated with Presentation Logic.
Differences Between forward() and include()
be forwarded to Inbox Page.
Differences Between forward() and sendRedirect()
| Side. Hence Client aware of which Servlet is | won't work outside of Server. |
|---|
providing the required Response.
Differences Between forward() and sendRedirect()
OR outside of Server.
Differences Between forward() and sendRedirect()
| communicate outside of Server. | between the Components is possible in the form |
|---|
of Request scoped Attributes.
Differences Between forward() and sendRedirect()
| in Redirection. Hence Information sharing | 5) No extra trip is required to the Client and |
|---|---|
| between the Components is not possible. | Hence there are no Network Traffic and |
Performance Problems.
Differences Between forward() and sendRedirect()
| Client Side. Hence Network Traffic increases and | 6) By using RequestDispatcher Object we can |
|---|---|
| creates Performance Problems. | implement Forward Mechanism. |
| 6) By using HttpServletResponse Object we can | rd.forward() |
implement sendRedirection.
resp.sendRedirection()
- Every example is complete and compiles as-is
- Examples are grouped by topic
- Typing programs is the fastest way to learn servlets