Nearby lessons

30 of 34

Servlet - Examples: ServletContext & RequestDispatcher

📌 What You Will Learn
  • 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()

Example01
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

Example02
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>

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

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

ServletConfig

time of Servlet Object Destruction.

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

ServletConfig

ServletConfig config = getServletConfig();

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

ServletConfig

provided by Web Server Vendor.

Example07
JCode Cell
1 
2 It 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()

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

ServletContext

Application Level Configuration Information.

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

ServletContext

of Application Undeployment.

Example10
JCode Cell
1 
2 Context 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

provided by Web Server Vendor.

Example11
JCode Cell
1 
2 It 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 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.

Example12
JCode Cell
1 
2 On 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 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.

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

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.

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

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 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 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:

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.

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

Application Scope

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

Values ---- String

Example16
JCode Cell
1 
2 Attributes are not Deploy time Constants.
3 Parameters are Deployment Time Constants.
4 Attributes are Key - Value Pairs where Key is
5 Parameters 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?

Example17
JCode Cell
1 
2 At the time of retrieval we should perform
3 At 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.

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

Example19
JCode Cell
1 
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4 import java.io.*;
5 import javax.servlet.annotation.*;
6 @WebServlet("/test")
7 public class UsersCount extends HttpServlet
8 {
9 public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
10 {
11 PrintWriter out = resp.getWriter();
12 ServletContext context = getServletContext();
13 Integer count = (Integer)context.getAttribute("usercount");
14 HttpSession session = req.getSession();
15 if(session.isNew())
16 {
17 if(count == null)
18 {
19 count = 1;
20 }
21 else
22 {
23 count++;
24 }
25 context.setAttribute("usercount",count);
26 }
27 out.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?

Example20
JCode Cell
1 
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4 import java.io.*;
5 import javax.servlet.annotation.*;
6 @WebServlet("/test")
7 public class SessionHitCountDemo extends HttpServlet
8 {
9 public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
10 {
11 PrintWriter out = resp.getWriter();
12 HttpSession session = req.getSession();
13 Integer count = (Integer)session.getAttribute("hitcount");
14 if(count == null)
15 {
16 count =1;
17 }
18 else
19 {
20 count++;
21 }
22 session.setAttribute("hitcount",count);
23 out.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 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.

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

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.

Example22
JCode Cell
1 
2 public 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
Example23
JCode Cell
1 
2 public 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

Example24
JCode Cell
1 
2 We 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.

Example25
JCode Cell
1 
2 By 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.

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

By ServletContext Object

Example27
JCode Cell
1 
2 public void forward(SR req,SR resp)throws SE,IOE
3 public void include(SR req,SR resp)throws SE,IOE
4

Demo Program 1 to forward

Example28
JCode Cell
1 
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4 import java.io.*;
5 import javax.servlet.annotation.*;
6 @WebServlet("/test1")
7 public class FirstServlet extends HttpServlet
8 {
9 public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
10 {
11 PrintWriter out=resp.getWriter();
12 out.println("<h1>This is First Servlet</h1>");
13 RequestDispatcher rd = req.getRequestDispatcher("/test2");
14 rd.forward(req,resp);
15 }
16 }
17
Output

    <h1>This is First Servlet</h1>
          

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.

Example29
JCode Cell
1 
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4 import java.io.*;
5 import javax.servlet.annotation.*;
6 @WebServlet("/test2")
7 public class SecondServlet extends HttpServlet
8 {
9
10 public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
11 {
12 PrintWriter out=resp.getWriter();
13 out.println("<h1>This is Second Servlet</h1>");
14
15 }
16 }
17
Output

    <h1>This is Second Servlet</h1>
          

Demo Program 2 to forward

Example30
JCode Cell
1 
2 <h1> This is forward demo</h1>
3 <form action = "/advapps3D/test1" >
4 Enter Name :<input type=text name=uname><br>
5 Enter Password :<input type=text name=pwd><br>
6 <input type=submit>
7 </form>
8

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.

Example31
JCode Cell
1 
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4 import java.io.*;
5 import javax.servlet.annotation.*;
6 @WebServlet("/test1")
7 public class ValidateServlet extends HttpServlet
8 {
9 public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
10 {
11 String name = req.getParameter("uname");
12 String pwd = req.getParameter("pwd");
13 if(name.equals("Durga") && pwd.equals("scwcd"))
14 {
15 ServletContext context=getServletContext();
16 RequestDispatcher rd =context.getRequestDispatcher("/inbox.jsp");
17 rd.forward(req,resp);
18 }
19 else
20 {
21 RequestDispatcher rd =req.getRequestDispatcher("/error.jsp");
22 rd.forward(req,resp);
23 }
24
25 }
26 }
27

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.

Example32
JCode Cell
1 
2 public class HelloServlet extends HttpServlet
3 {
4 public void doGet(..)...
5 {
6 PrintWriter out=resp.getWriter();
7 out.println("This is required response");
8 out.flush();//commiting the response
9 RD rd = req.getRD("/test2");
10 rd.forward(req,resp);//RE: ISE
11 }
12 }
13
Output

    This is required response
          

SS

f secondservlet response

Example33
JCode Cell
1 
2 public class FirstServlet extends HttpServlet
3 {
4 public void doGet(..)...
5 {
6 PrintWriter out=resp.getWriter();
7 RequestDispatcher rd=req.getRequestDispatcher("/test2");
8 rd.forward(req,resp);
9 System.out.println("After forward control comes back");// it will printed in the serverconsole
10 out.println("Hello this is FirstServlet again");//This line ignored by web container
11 System.out.println(10/0);// AE information will be displayed to the end user instead o
12

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

Example34
JCode Cell
1 
2 }
3 }
4

FirstServlet.java

Example35
JCode Cell
1 
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4 import java.io.*;
5 import javax.servlet.annotation.*;
6 @WebServlet("/test1")
7 public class FirstServlet extends HttpServlet
8 {
9 public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
10 {
11 req.setAttribute("durga","java");
12 ServletContext context=getServletContext();
13 RequestDispatcher rd = req.getRequestDispatcher("/test2");
14 rd.forward(req,resp);
15 }
16 }
17

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.

Example36
JCode Cell
1 
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4 import java.io.*;
5 import java.util.*;
6 public class ForwardAttributeDemo extends HttpServlet
7 {
8
9 public void doGet(HttpServletRequest req,HttpServletResponse resp) throwsServletException,IOException
10 {
11 PrintWriter out = resp.getWriter();
12 out.println("<h1>Forward Request Attributes</h1>");
13 Enumeration e = req.getAttributeNames();
14 while(e.hasMoreElements())
15 {
16 String name= (String)e.nextElement();
17 Object value = req.getAttribute(name);
18 out.println(name+"....."+value+"<br>");
19 }
20 }
21 }
22

Demo Program for include

Example37
JCode Cell
1 
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4 import java.io.*;
5 import javax.servlet.annotation.*;
6 @WebServlet("/test1")
7 public class FirstServlet extends HttpServlet
8 {
9 public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
10 {
11 PrintWriter out=resp.getWriter();
12 out.println("<h1>Hello This is FirstServlet</h1>");
13 RequestDispatcher rd=req.getRequestDispatcher("/test2");
14 rd.include(req,resp);
15 out.println("<h1>Hi This is First Servlet again</h1>");
16 }
17 }
18
Output

    <h1>Hello This is FirstServlet</h1>
    <h1>Hi This is First Servlet again</h1>
          

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...

Example38
JCode Cell
1 
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4 import java.io.*;
5 import javax.servlet.annotation.*;
6 @WebServlet("/test")
7 public class SecondServlet extends HttpServlet
8 {
9 public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
10 {
11 PrintWriter out=resp.getWriter();
12 out.println("<h1>This is Second Servlet</h1>");
13 }
14 }
15
Output

    <h1>This is Second Servlet</h1>
          

FirstServlet.java (advapps3H)

Example39
JCode Cell
1 
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4 import java.io.*;
5 import javax.servlet.annotation.*;
6 @WebServlet("/test1")
7 public class FirstServlet extends HttpServlet
8 {
9 public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
10 {
11 ServletContext context=getServletContext();
12 ServletContext fc=context.getContext("/advapps3I");
13
14 RequestDispatcher rd=fc.getRequestDispatcher("/test2");
15 rd.forward(req,resp);
16 }
17 }
18

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.

Example40
JCode Cell
1 
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4 import java.io.*;
5 import javax.servlet.annotation.*;
6 @WebServlet("/test2")
7 public class SecondServlet extends HttpServlet
8 {
9 public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
10 {
11 PrintWriter out=resp.getWriter();
12 out.println("<h1>This is Second Servlet..You can access by Foreign Request Dispatcher</h1>");
13 }
14 }
15
Output

    <h1>This is Second Servlet..You can access by Foreign Request Dispatcher</h1>
          

Differences Between forward() and include()

responsible to provide Response.

Example41
JCode Cell
1 
2 In the case of Forward, ForwardedServlet (S -
3 is responsible to provide complete Response. 2) In the case of Include, IncludingServlet (S - 1) is
4

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

Example42
JCode Cell
1 
2 Within the same Servlet, we can call forward()
3

Differences Between forward() and include()

Object. It is allowed to change Response Headers4) In the case of Include, IncludingServlet (S - 1)
also.having complete Control on the Response Object.

It is allowed to change Response Headers also.

Example43
JCode Cell
1 
2 In the case of Forward, ForwardedServlet (S - restrictions.
3 having complete Control on the Response
4

Differences Between forward() and include()

allowed to perform Forward, otherwise we willallowed to perform Include.

get

RE: IlleagalStateException.6) Include Mechanism can be used frequently in
6) Forward Mechanism can be used frequently inJSP's

Servlets because it is associated with processing. because it is associated with Presentation Logic.

Example44
JCode Cell
1 
2 After committing the Response, we are not 5) After committing the Response, we are
3

Differences Between forward() and include()

be forwarded to Inbox Page.

Example45
JCode Cell
1 
2 Eg: We required to Include Header Information
3 Eg: After validating User, the Request should and Footer Information in the Current Response.
4

Differences Between forward() and sendRedirect()

Side. Hence Client aware of which Servlet iswon't work outside of Server.

providing the required Response.

Example46
JCode Cell
1 
2 Redirection Mechanism will work at Client 2) Forward will work only within the Server and
3

Differences Between forward() and sendRedirect()

OR outside of Server.

Example47
JCode Cell
1 
2 It is the Best Choice if we want to
3 Redirection will work either within the Server communicate within Server.
4

Differences Between forward() and sendRedirect()

communicate outside of Server.between the Components is possible in the form

of Request scoped Attributes.

Example48
JCode Cell
1 
2 The same Request Object will be forwarded to
3 It is the Best Choice if we want to the SecondServlet and hence Information sharing
4

Differences Between forward() and sendRedirect()

in Redirection. Hence Information sharing5) No extra trip is required to the Client and
between the Components is not possible.Hence there are no Network Traffic and

Performance Problems.

Example49
JCode Cell
1 
2 A separate New Request Object will be created
3

Differences Between forward() and sendRedirect()

Client Side. Hence Network Traffic increases and6) By using RequestDispatcher Object we can
creates Performance Problems.implement Forward Mechanism.
6) By using HttpServletResponse Object we canrd.forward()

implement sendRedirection.

resp.sendRedirection()

Example50
JCode Cell
1 
2 In this Approach an extra trip is required to the
3
📝 Key Takeaways
  • Every example is complete and compiles as-is
  • Examples are grouped by topic
  • Typing programs is the fastest way to learn servlets