Methods getRequestDispatcher() and sendRedirect()

The two important methods in Servlet Programming are: getRequestDispatcher() and sendRedirect(). Their descriptions are given below.

 

1. getRequestDispatcher()

A RequestDispatcher object can forward a client’s request to a resource or include the resource itself in the response back to the client. A resource can be another Servlet, or an HTML file, or a JSP file, etc. We can also think of a RequestDispatcher object as a wrapper for the resource located at a given path that is supplied as an argument to the getRequestDispatcher method.

For constructing a RequestDispatcher object in Servlet Programming, we can use either the ServletRequest.getRequestDispatcher() method or the method ServletContext.getRequestDispatcher(). They both do the same thing, but impose slightly different constraints on the argument path. For the former, it looks for the resource in the same web application to which the invoking Servlet belongs and the path-name specified can be relative to invoking servlet. For the latter, the path-name must begin with ‘/’ and is interpreted relative to the root of the web application.

To illustrate, suppose we want Servlet A to invoke a.jsp. If they are both in the same directory, we could accomplish this by incorporating the following code fragment in either the service() method or the doGet()/doPost() method of Servlet A:

RequestDispatcher v = request.getRequestDispatcher("a.jsp");
v.forward(request, response);

Where request of the type HttpServletRequest, is the first parameter of the enclosing service() method (or the doGet() method) and response, of type HttpServletResponse, the second.

We could accomplish the same by:

RequestDispatcher v = getServletContext().getRequestDispatcher(“/a.jsp");
view.forward(request, response);

 

For implementation, we could modify the web application CookieExample and rename it to Advanced. Here the codes of k.html and GetCookiesServlet.java are remaining unchanged. But the code of GetCookiesServlet.java is modified for our purposes. In addition, a new JSP file check.jsp is included to the web application.

The example code are placed within Advanced directory.

 

AddCookieServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class AddCookieServlet extends HttpServlet {
 
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

   // Get parameter from HTTP request.
    String data = request.getParameter("data");

    // Create cookie.
   Cookie cookie = new Cookie("techguru", data);

    // Add cookie to HTTP response.
    response.addCookie(cookie);

    // Lets a JSP make the response page.
    RequestDispatcher view = request.getRequestDispatcher("check.jsp");
    view.forward(request,response);
  }

}

check.jsp

<html>
<body>
<a href="GetCookiesServlet.do">Click Here</a>
</body>
</html>

 

The output is shown below:

 

 

 

 

 

 

 

 

On clicking the “Submit” button will produce the following result:

 

 

 

 

 

 

 

 

Now on clicking the hyperlink named Click Me will help us retrieving the result produced by the Servlet code GetCookiesServlet.java. See it below:

 

 

 

 

 

 

 

 

 

2. sendRedirect()

In response.sendRedirect() whenever the client makes any request it goes to the container, there the container decides whether the concerned Servlet can handle the request or not. If not then the Servlet decides that the request can be handled by other Servlet or JSP. Then the Servlet calls the sendRedirect() method of the response object and sends back the response to the browser along with the status code. Then the browser sees the status code and looks for that Servlet which can now handle the request. Again the browser makes a new request, but with the name of that Servlet which can now handle the request and the result will be displayed to us by the browser. The URL will have the address of the new servlet. In all this process the client is unaware of the processing.

Therefore when we want that someone else should handle the response of our Servlet, then there we should use sendRedirect() method. Servlet Redirect forces the browser to do the work. The example code are placed within ServletProject directory.

The complete code is given below:

welcome.html

<html>
<body>
      <form action = "/ServletProject/SendRedirect" method = "post">
      <tr>
            <td>Enter your name :</td>
            <td><input type = "text" name = "username"></td>
      </tr><br>
      <tr>
            <td>Enter your password :</td>
            <td><input type = "password" name = "password"></td>
      </tr><br>
      <tr>
            <td><input type = "submit" name = "Submit"></td>
      </tr>
      </form>
</body>
</html>

 

SendRedirect.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class SendRedirect extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

      PrintWriter pw = response.getWriter();
     String name = request.getParameter("username");
      String password = request.getParameter("password");

     if(name.equals("techguru") && password.equals("system123")) {
       response.sendRedirect("/ServletProject/ValidUser");
      }
     else {
          pw.println("You are not a valid user");
      }
   }

}

 

 ValidateUser.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class ValidateUser extends HttpServlet  {

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

    PrintWriter pw = response.getWriter();
    pw.println("Welcome to My Site!!");
    pw.println("\nHow are you?");
  }

}

 

web.xml

<web-app>
<servlet>
   <servlet-name>amt</servlet-name>
   <servlet-class>SendRedirect</servlet-class>
</servlet>
  <servlet>
   <servlet-name>amt1</servlet-name>
   <servlet-class>ValidUser</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>amt</servlet-name>
   <url-pattern>/SendRedirect</url-pattern>
</servlet-mapping>
<servlet-mapping>
   <servlet-name>amt1</servlet-name>
   <url-pattern>/ValidUser</url-pattern>
</servlet-mapping>
</web-app>

 

The output is shown below:

 

 

 

 

 

 

 

 

On clicking the “Submit” button it will produce the following result:

 

 

 

 

 

 

 

 

But if either the username (techguru) or the password (system123) is found to be wrong, then it will produce a different output:

 

 

♦ Differences between getRequestDispatcher() and sendRedirect():

Both kinds of redirections are useful, depending on the precise effect we want. But the key difference between getRequestDispatcher and sendRedirect() is that one is server side and the other is client side, but this has some important implications:

(1) If we use a RequestDispatcher, the target Servlet/JSP receives the same request/response objects as the original Servlet/JSP. Therefore, we can pass data between them using request.setAttribute(). With a sendRedirect(), it is a new request from the client, and the only way to pass data is through the session or with web parameters (url?name=value).

(2) A sendRedirect() also updates the browser history. Suppose we have JSP-1 which has a form that targets Servlet-2, which then redirects to JSP-3. With a redirect, the user’s address bar will read “http://[host]/JSP-3“. If the user clicks the Reload/Refresh button, only JSP-3 will be re-executed, not Servlet-2.

If we use a RequestDispatcher to forward from Servlet-2 to JSP-3, the user’s address bar will read “http://[host]/Servlet-2“. A Reload/Refresh will execute both Servlet-2 and JSP-3. This can be important if Servlet-2 performs some system update (such as credit-card processing).