Servlet RequestDispatcher And SendRedirect

There are two methods in servlet to dispatch user requests to other web resources such as JSP, HTML, or another servlet in the same or different web applications. They are RequestDispatcher interface and HttpServletResponse‘s sendRedirect() method.

RequestDispatcher is used to dispatch requests to the resource run in the same web applications, and sendRedirect() can be used to redirect client users to request other web application’s resources. In this article, you can learn how to use them and the difference between them by examples.

1. How to get RequestDispatcher object.

HttpServletRequest provides getRequestDispatcher(String targetResourceUrl) method, this method will return an object of RequestDispatcher type. The targetResourceUrl parameter is the jsp path locator(/pages/login/login.jsp) or servlet mapping path(HelloWorld) etc.

1.1 RequestDispatcher methods.

  1. forward(ServletRequest request, ServletResponse response): This method is used to forward the current requests to another resource such as JSP, Html, or another servlet in the same web server. Then another resource’s response will return back to the client. This action is done completely on the server-side. The client-side does not know which resource that has been forwarded to.
  2. include(ServletRequest request, ServletResponse response): This method can be used to include another web resource’s response in the current web resource’s response and then send them back together to the client. This also occurred totally on the server-side.

1.2 Example of using RequestDispatcher.

  1. Below is the example project file structures.
    D:\WORK\DEV2QA.COM-EXAMPLE-CODE\WEBAPPLICATIONEXAMPLEPROJECT
    ├─src
    │  └─com
    │      └─dev2qa
    │          └─example
    │              │
    │              ├─servletrequest
    │              │      GetRequestParameter.java
    │              │      RequestDispatch.java
    │
    └─WebContent
        │
        ├─pages
        │  ├─common
        │  │      showMessage.jsp
        │  │
        │  ├─login
        │  │      login.jsp
        │  │      loginSuccess.jsp
        │  │      loginSuccessBySendRedirect.jsp
        │
        └─WEB-INF
                web.xml
  2. /pages/login/login.jsp: This is the login JSP page, user input the username and password and clicks the submit button to call the RequestDispatch servlet. If the user account is not correct then use RequestDispatcher‘s include() method to go to the login.jsp again and show an error message.
    <%
    /* Get and show error message if user account is not correct.*/
    String message = "";
    Object messageObj = request.getAttribute("message");
    if(messageObj!=null)
    {
     message = (String)messageObj;
    }
    %>
    
    <%=message %>
    <form action="/Dev2qaWebAppExample/RequestDispatch" method="post">
    <input type="hidden" name="action" value="useRequestDispatcher" />
    UserName: <input type="text" id="userName" name="userName"/><br/>
    Password: <input type="password" id="password" name="password"/><br/>
    <input type="submit" value="Submit"/>
    </form>
  3. /pages/login/loginSuccess.jsp: When the user inputs the correct account (user name and password are all “dev2qa.com”), then RequestDispatch servlet will use RequestDispatcher‘s forward() method to direct user request to this page, it will show login success messages on the page.
    <%
    /* Get and show success message if user account is correct.*/
    String message = "";
    Object messageObj = request.getAttribute("message");
    if(messageObj!=null)
    {
     message = (String)messageObj;
    }
    %>
    
    <%=message %>
  4. RequestDispatch.java: This is the servlet that invoked by login.jsp page form submit. In the doGet() method, it will check whether to use RequestDispatcher or sendRedirect() to dispatch the result page to client. If use RequestDispatcher then when user account is correct it will use RequestDispatcher’s forward() method,  when user account is wrong it will use RequestDispatcher’s include() method.
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     
       /* action value is "useRequestDispatcher" or "useSendRedirect". Use this to switch to different method.*/
       String action = req.getParameter("action");
    
       if("useRequestDispatcher".equalsIgnoreCase(action))
       {
          this.useRequestDispatcher(req, resp);
       }else if("useSendRedirect".equalsIgnoreCase(action))
       {
          this.useSendRedirect(req, resp);
       }
    
    }
    
    
     private void useRequestDispatcher(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
     {
    
        String userName = req.getParameter("userName");
    
        String password = req.getParameter("password");
    
        /* Get web application context path, this is the root path for web application in page url,
    
        * it's value is Dev2qaWebAppExample in this example.*/
    
        String contextPath = req.getServletContext().getContextPath();
    
        if("dev2qa.com".equalsIgnoreCase(userName) && "dev2qa.com".equalsIgnoreCase(password))
        {
    
           /* If account data is correct.*/
    
           /* Get loginSuccess.jsp page url we want to dispatch to.*/
    
           String targetUrl = "/pages/login/loginSuccess.jsp";
    
           RequestDispatcher rd = req.getRequestDispatcher(targetUrl);
    
           /* Set message value, the loginStatus.jsp will show this message on the web page.*/
    
           req.setAttribute("message", "Your username and password is correct.");
    
           /* Forward to the target jsp page.*/
    
           rd.forward(req, resp); 
    
        }else
        {
    
           /* If account data is not correct*/
    
           /* Get login.jsp page url we want to dispatch to.*/
    
           String targetUrl = "/pages/login/login.jsp";
    
           RequestDispatcher rd = req.getRequestDispatcher(targetUrl);
    
           /* Set message value, the loginStatus.jsp will show this message on the web page.*/
    
           req.setAttribute("message", "Your username and password is not correct, please login again.");
    
           /* Include login.jsp page to let user login again.*/
    
           rd.include(req, resp); 
    
       }
    
     }
  5. When you run the example above, you can see below web pages. The URL in the below picture is just the RequestDispatch servlet URL. So the RequestDispatcher will forward or include the target web resource totally at the server-side. The Client-side does not know which resource has been forwarded or included.
  6. Login success page.
    login-success-page
  7. Login fails page.
    login-fail-page

2. HttpServletResponse’s sendRedirect().

  1. This method can be used to send the request back to the client and let the client request the returned web resources in the same web container or different web container.
  2. Example of use sendRedirect(). Below is the example file structure that demos the sendRedirect() method.
    D:\WORK\DEV2QA.COM-EXAMPLE-CODE\WEBAPPLICATIONEXAMPLEPROJECT
    ├─src
    │  └─com
    │      └─dev2qa
    │          └─example
    │              │
    │              ├─servletrequest
    │              │      GetRequestParameter.java
    │              │      RequestDispatch.java
    │
    └─WebContent
        │
        ├─pages
        │  ├─common
        │  │      showMessage.jsp
        │  │
        │  ├─login
        │  │      login.jsp
        │  │      loginSuccess.jsp
        │  │      loginSuccessBySendRedirect.jsp
        │
        └─WEB-INF
                web.xml
  3. /pages/login/loginSuccessBySendRedirect.jsp: When login account is correct, then use sendRedirect() in RequestDispatch servlet to let client request this jsp page. And message will be transferred to this jsp file by using request parameter in url.
    <%
    /* Get and show success message if user account is correct.*/
    String message = request.getParameter("message");
    %>
    
    <%=message %>
  4. RequestDispatch.java: Add useSendRedirect() method. If login success then redirects the client to make a new request to the page loginSuccessBySendRedirect.jsp. If login fails then redirect the client to request http://www.yahoo.com. Because sendRedirect() will let client to send another request, so HttpServletRequest setAttribute() method will not take effect. We have to add a message in the target URL as a request parameter to transfer it to the next web resource.
     private void useSendRedirect(HttpServletRequest req, HttpServletResponse resp) throws IOException
     {
         String userName = req.getParameter("userName");
         String password = req.getParameter("password");
     
         /* Get web application context path, this is the root path for web application in page url,
         * it's value is Dev2qaWebAppExample in this example.*/
         String contextPath = req.getServletContext().getContextPath();
     
         /* Because need client to send the request again, so need to add web application context path root in target url.*/
         String targetUrl = contextPath;
     
         if("dev2qa.com".equalsIgnoreCase(userName) && "dev2qa.com".equalsIgnoreCase(password))
         {
             /* If account data is correct.*/
     
             /* Because sendRedirect() will let client send request again so req.setAttribute() will not take effect.
             * We should add the message as the request parameter in target url.
             req.setAttribute("message", "Your username and password is correct."); */
             targetUrl += "/pages/login/loginSuccessBySendRedirect.jsp?message=Your username and password is correct.";
         }else
         {
             /* If account data is not correct then send request page to yahoo.com*/
             targetUrl = "http://www.yahoo.com";
         }
     
         /* Let client to request targetUrl.*/
         resp.sendRedirect(targetUrl);
     }
  5. To run the example, you need first to change the action value to “useSendRedirect” in login.jsp as below.
    <form action="/Dev2qaWebAppExample/RequestDispatch" method="post">
    <!-- input type="hidden" name="action" value="useRequestDispatcher" / -->
    <input type="hidden" name="action" value="useSendRedirect" />
    UserName: <input type="text" id="userName" name="userName"/><br/>
    Password: <input type="password" id="password" name="password"/><br/>
    <input type="submit" value="Submit"/>
    </form>
  6. You can see that the page URL is changed after using the sendRedirect() method.
    page-url-changed-after-send-redirect

3. Difference between RequestDispatcher  and  HttpServletResponse sendRedirect().

3.1 RequestDispatcher.

  1. Has two methods forward() and include()
  2. Run and can only run at web server side.
  3. The client-side does not know which web resource has been dispatched.
  4. Can not dispatch to web resources run in another web container.
  5. Can transfer variable by using HttpServletRequest.setAttribute() method.

3.2 sendRedirect().

  1. Run at the client-side. Let the client-side make a new request to another URL.
  2. Can dispatch to web resources in the same or different web container.
  3. Can transfer variable by using URL request parameters in target URL.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.