10 - Request Redirect and Forward in Servlets

10.1 Overview

In previous chapters we discussed how to use servlets for various scenarios but all of the examples have one servlet. In any web application, there are multiple screens and servlets and together they form a web application.

In this chapter we will discuss how to forward a control from a servlet.

10.2 Approaches

There are two approaches with which a servlet can pass the control to another servlet or JSP or to outside the web application.

  1. Request forward
  2. Redirect

10.3 Request Forward

With request forward ,a Servlet can forward the control to resources available within the web application. That means which Request forward, servlet can forward the request to another servlet of JSP which are part of same web application.

This transfer of control is done by the container internally and browser or client is not involved in the process.

When the forward is done, the original request and response objects are forwarded so attributes available in request will be carried as well.

To Forward a request ,  RequestDispatcher object is needed which can be obtained either

  1. by request object -means the dispatch is relative to the current URL

RequestDispatcher rd  = request.getRequestDispatcher(“url”);

rd.forward(request,response);

  1. by Servlet Context Object - means the dispatch is relative to the root of the ServletContext.

RequestDispatcher rd  = getServletContext.getRequestDispatcher(“url”);

rd.forward(request,response);

In both cases url is the value where the control needs to be forwarded.

Refer Section 10.6 for examples

10.4 Redirect

This approach generally is used when the control needs to be forwarded outside the web application. For example we need to forward the control to google.com . It does not mean that we cannot use redirect within same web application , but this approach is ideally used to redirect control to different domain.

This transfer of control task is delegated to the browser by the container. That is, the redirect sends a header back to the browser / client.

Since it is a new request, the old request and response object is lost.

To redirect a request, sendRedirect(“url”) API needs to be called from response.

response.sendRedirect(“url”);

Refer Section 10.6 for examples.

10.5 Difference between Forward and Redirect

a) Forward is intended to forward a request to resources within the web application where Redirect should be used to send control outside the web application.

b) In forward, request and response objects are forwarded which means attributes stored in request are carried as well where as in case of redirect it is new request so all attributes are lost.

c) In forward, control is forwarded by container and browser is not involved where as in redirect, browser takes the responsibility. To validate this , in case of forward, browser URL is not changed but gets changed while redirect.

10.6 Examples

10.6.1 – Write a program that explains the request forward concept.

Solution – To explain the request forward , let’s 

  1. create two servlets (SourceServlet and Destination Servlet) .
  2.  Source Servlet will print some message on server console and stores some attributes in request and forward the control to Destination Servlet.
  3. Destination Servlet will print the message along with the attributes stored by Source Servlet.
  1.  Add Servlet entries in web.xml
<servlet>
    <servlet-name>SourceServlet</servlet-name>
    <servlet-class>com.servlet.tutorial.SourceServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>SourceServlet</servlet-name>
    <url-pattern>/SourceServlet</url-pattern>
</servlet-mapping>
<servlet>
    <servlet-name>DestinationServlet</servlet-name>
    <servlet-class>com.servlet.tutorial.DestinationServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>DestinationServlet</servlet-name>
    <url-pattern>/DestinationServlet</url-pattern>
</servlet-mapping>
    

b. Write Servlet Code

package com.servlet.tutorial;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SourceServlet extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    {
        System.out.println("Welcome Message : Source Servlet");
        request.setAttribute("Request-Attribute", "Value of Attribute ");
        RequestDispatcher rd = request.getRequestDispatcher("/DestinationServlet");
        rd.forward(request, response);
    }   
}               
package com.servlet.tutorial;   
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;                  
public class DestinationServlet extends HttpServlet {                                                                           
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        System.out.println("Welcome Message : Destination Servlet");
        Object attributeValue = request.getAttribute("Request-Attribute");
        System.out.println("Value of Request-Attribute is : " + attributeValue);
    }   
}               

Testing-

Hit the url http://localhost:8080/HelloWorld/SourceServlet in browser. This will print the messages on server console. Note that url of browser is not changed and request attribute is available in Destination Servlet.

10.6.2  Write a program to demonstrate our understanding on Redirect?

Solution – For this lets write a Servlet  “RedirectServlet” which will

  1. Prints the  welcome message on server console
  2. Stores a request attribute
  3. Redirects to Destination Servlet (created in section 10.6.1 ) which will print welcome message and request attribute value
  1. Add Servlet Entry in web.xml
<servlet>
    <servlet-name>RedirectServlet</servlet-name>
    <servlet-class>com.servlet.tutorial.RedirectServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>RedirectServlet</servlet-name>
    <url-pattern>/RedirectServlet</url-pattern>
</servlet-mapping>

b. Write RedirectServlet Code

package com.servlet.tutorial;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RedirectServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
    System.out.println("Welcome Message : Redirect Servlet");
    request.setAttribute("Request-Attribute", "Value of Attribute ");
    response.sendRedirect("DestinationServlet");
}
}

Testing 

Hit the Url http://localhost:8080/HelloWorld/RedirectServlet . Once you hit , URL will be changed to http://localhost:8080/HelloWorld/DestinationServlet and on server console , request attribute will not found

10.6.3 – Change the Redirect Servlet written in Section 10.6.2 to  redirect to google.com

Solution –

package com.servlet.tutorial;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RedirectServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
{
    System.out.println("Welcome Message : Redirect Servlet");
    request.setAttribute("Request-Attribute", "Value of Attribute ");
    response.sendRedirect("http://www.google.com");
}
}

Testing –

Hit the Url http://localhost:8080/HelloWorld/RedirectServlet . Once you hit , URL will be changed to google.com and google will be opened.

 

10.6.4 – Update SourceServlet (written in Section 10.6.1) to forward to home.html instead of Destination Servlet

Solution –

a. create home.html with static message inside WebContent directory

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Home Page </title>
</head>
<body>
<H1> Source Servlet forwarded control to home.html
</body>
</html>

b. Update SourceServlet

package com.servlet.tutorial;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SourceServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
    System.out.println("Welcome Message : Source Servlet");
    RequestDispatcher rd = request.getRequestDispatcher("/home.html");
    rd.forward(request, response);
}   
}

Testing

Hit the http://localhost:8080/HelloWorld/SourceServlet. It forwards the control to home.html and url is not changed.

10.7 Conclusion

In this chapter we learned the different approaches, their usage and difference of forwarding the control from servlet to another servlet, another jsp/html or to entire new domain.

Like us on Facebook