Download Java Servlets: Request Dispatching and Including - Servlet Examples and more Lecture notes Web Design and Development in PDF only on Docsity!
Web Design and Development CS-
Lecture 30
Dispatching Requests
In this handout we will start with request dispatching techniques and give some examples
related to that. Further more some methods of HttpResponse and HttpRequest
will also be discussed. Finally, this handout will be concluded by discussing the
importance of session tracking. Before starting, let’s take a look at the summery of the
previous lecture.
Recap
In the previous lecture we had some discussion about Response Redirection and Request
Dispatcher. We said that Response Redirection was used to redirect response of the
Servlet to another application resource. This resource might be another Servlet or any JSP
page.
Two forms of Response redirection were discussed. These were:
Sending a standard request:
Using response.sendRedirect(“path of resource”) method, a
new request is generated which redirects the user to the given URL. If the URL is
of another servlet, that second servlet will not be able to access the original
request object.
Redirection to an error page:
An error code is passed as a parameter along with message to
response.sendError(int, msg) method. This method redirects the
user to the particular error page in case of occurrence of specified error.
Similarly request dispatching provides us the facility to forward the request processing to
another servlet, or to include the output of another resource (servlet, JSP or HTML etc)
in the response. Unlike Response Redirection, request object of calling resource is
available to called resource. The two ways of Request Dispatching are:
Forward:
Forwards the responsibility of request processing to another resource.
Include:
Allows a servlet to include the results of another resource in its response. So
unlike forward, the first servlet to receive the request is the one which finishes the
response.
Web Design and Development CS-
Example Code: Request Dispatching - include
Lets start with the example of include. We will see how a Servlet includes the output of
another resource in its response. The following example includes a calling Servlet
MyServlet and Servlet IncludeServlet, who’s output will be included in the
calling Servlet.
The code of MyServlet.java servlet is given below.
MyServlet.java
import java.io.; import java.net.; import javax.servlet.; import javax.servlet.http.;
public class MyServlet extends HttpServlet {
/* this method is being called by both doGet() and doPost().We usually follow this practice, when we are not sure about the type of incoming request to the servlet. So the actual processing is being done in the processRequest(). */ protected void processRequest (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html"); PrintWriter out = response.getWriter();
out.println(""); out.println(""); out.println("Start of include request "); out.flush();
// getting the object of ServletContext, that will be used to // obtain the object of RequestDispacther ServletContext context = getServletContext();
// getting the object of RequestDispatcher by passing the path // of included resource as a parameter RequestDispatcher rd = context.getRequestDispatcher("/includeservlet");
// calling include method of RequestDispatcher by passing // request and response objects as parameters. This will execute //the second servlet and include its output in the first servlet rd.include(request, response);
/* the statements below will be executed after including the output of the /includeservlet */
out.println("End of include request "); out.println("");
Web Design and Development CS-
protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); }
} // end IncludeServlet
In the processRequest(), firstly we get the PrintWriter stream from the
HttpServletResponse object. Then we include an HTML tag to the output of the
calling servlet. One thing that must be considered is that PrintWriter stream is not
closed in the end, because it is the same stream that is being used in the calling servlet
and this stream may also be used in the calling servlet again. So, if it is closed over here,
it can not be used again in the calling servlet.
web.xml
MyServlet MyServlet
IncludeServlet IncludeServlet
MyServlet /myservlet
IncludeServlet /includeservlet
I
Web Design and Development CS-
Code Example: Request Dispatcher - forward
As discussed earlier, we can forward the request processing to another resource using
forward method of request dispatcher. In this example, the user enters his/her name and
salary on the index.html and submits the form to FirstServlet, which
calculates the tax on salary and forwards the request to another servlet for further
processing i.e. SecondServlet.
index.html
Enter your name
Salary
I
FirstServlet.java
import java.io.; import java.net.; import javax.servlet.; import javax.servlet.http.;
public class FirstServlet extends HttpServlet {
// this method is being called by both doGet() and doPost() protected void processRequest(HttpServletRequest request, HttpServletResponse response) sthrows ServletException, IOException {
// getting value of salary text filed of the HTML form String salary = request.getParameter("salary");
// converting it to the integer. int sal = Integer.parseInt(salary);
// calculating 15% tax int tax = (int)(sal * 0.15);
Web Design and Development CS-
SecondServlet.java
import java.io.; import java.net.; import javax.servlet.; import javax.servlet.http.;
public class SecondServlet extends HttpServlet {
// this method is being called by both doGet() and doPost() protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html"); PrintWriter out = response.getWriter();
// obtaining values of name and salary text fields of index.html String name = request.getParameter("name"); String salary = request.getParameter("salary");
/* getting attribute value that has been set by the calling servlet i.e. FirstServlet */ String tax = (String)request.getAttribute("tax");
// generating HTML tags using PrintWriter out.println(""); out.println(""); out.println("SecondServlet"); out.println(""); out.println(""); out.println(" Welcome " + name+ "");
out.println(" Salary " + salary+ ""); out.println(" Tax " + tax+ "");
out.println(""); out.println("");
out.close(); }
// This method is calling processRequest() protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } // This method is calling processRequest() protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } }
Web Design and Development CS-
web.xml
FirstServlet FirstServlet
SecondServlet SecondServlet
FirstServlet /firstservlet
SecondServlet /secondservlet
I
Web Design and Development CS-
HttpServletResponse Methods
Let’s discuss some methods of HttpServletResponse class
setContentType()
Almost every Servlet uses this header. It is used before getting the PrintWriter
Stream. It is used to set the Content Type that the PrintWriter is going to use.
Usually we set “text/html” , when we want to send text output or generate HTML tags on
the client’s browser.
setContentLength()
This method is used to set the content length. It takes length as an integer parameter.
addCookie()
This method is used to add a value to the Set-Cookie header. It takes a Cookie object as a
parameter and adds it to the Cookie-header. We will talk more about Cookies in the
session tracking part.
sendRedirect()
This method redirects the user to the specific URL. This method also accepts the relative
URL. It takes URL string as parameter and redirects the user to that resource.
Web Design and Development CS-
Session Tracking
Many applications require a series of requests from the same client to be associated with
one another. For example, any online shopping application saves the state of a user's
shopping cart across multiple requests. Web-based applications are responsible for
maintaining such state, because HTTP protocol is stateless. To support applications that
need to maintain state, Java Servlet technology provides an API for managing sessions
and allows several mechanisms for implementing sessions.
Before looking inside the session tracking mechanism lets see the limitation of HTTP
protocol to get the real picture of problems that can happen with out maintaining the
session.
Continuity problem- user’s point of view
Suppose a user logs on to the online bookshop, selects some books and adds them to his
cart. He enters his billing address and finally submits the order. HTTP cannot track
session as it is stateless in nature and user thinks that the choices made on page1 are
remembered on page
Page 1
Page 2
Page 3
Page 4
Server State
Added book to cart
Added book to cart
CC# = XXX Billing address
Order submitted & logged