Servlet RequestDispatcher And SendRedirect

There are two methods in servlet to dispatch user request 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 request to the resource run in same web applications, and sendRedirect() can be used to redirect client user to request other web application’s resource. In this article, you can learn how to use them and the difference between them by examples.

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.

RequestDispatcher methods

forward(ServletRequest request,ServletResponse response):
This method is used to forward current request to another resource such as jsp, html or other servlet in the same web server. Then another resource’s response will return back to the client. This action is done completely at server side. Client side do not know which resource that has been forwarded to.
servlet requestdispatcher's forward method

include(ServletRequest request,ServletResponse response):
This method can be used to include another web resource’s response in current web resource’s response and then send them back together to client. This also occurred totally at server side.
servlet requestdispatcher's include method
Example of using RequestDispatcher

You can download below example jsp page and java file in the article download attachment.

RequestDispatcher example file structure

  1. /pages/login/login.jsp:
    This is the login jsp page, user input username and password and click submit to call the RequestDispatch servlet. If user account is not correct then use RequestDispatcher’s include() method to go to login.jsp again and show 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>
  2. /pages/login/loginSuccess.jsp:
    When user input correct account (user name and password are all “dev2qa.com”), then RequestDispatch servlet will use RequestDispatcher’s forward() mtehod to direct user request to this page, it will show login success messages int 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 %>
  3. 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); 
    
     }
    
     }

When you run the example above, you can see below web page. The url in below picture is just the RequestDispatch servlet url. So the RequestDispatcher will forward or include the target web resource totally at server side. Client side do not know which resource has been forwarded or included.

READ :   Welcome File List And Load On Startup

Login success page.
login success page
Login fail page.
login fail page

HttpServletResponse’s sendRedirect()

This method can be used to send the request back to client and let client to request returned another web resources run in same web container or different web container.

Example of use sendRedirect()

sendRedirect code example

  1. /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 %>
  2. RequestDispatch.java:
    Add useSendRedirect() method. If login success then redirect client to make a new request to loginSuccessBySendRedirect.jsp. If login fail then redirect 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 message in the target url as request parameter to transfer it to 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);
     }
  3. To run the example you need fist change the action value to “useSendRedirect” in login.jsp.
    <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>

You can see that the page url changed after using sendRedirect().
page url changed after send redirect

READ :   Deploy And Undeploy Java EE Web Applications In Tomcat

Difference between RequestDispatcher  and  HttpServletResponse sendRedirect()

RequestDispatcher:

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

sendRedirect():

  1. Run at client side.Let client side to 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.

Download “Servlet-RequestDispatcher-And-SendRedirect-Example-Code.zip” Servlet-RequestDispatcher-And-SendRedirect-Example-Code.zip – Downloaded 80 times – 31 KB

(Visited 623 times, 1 visits today)

Leave a Reply

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.