Skip to content

Forwarding & Redirection


Concepts

  • Transferring control to a resource
  • Forwarding an HTTP Request to another resource
  • Redirecting a browser to another resource

Transferring

  • It is very typical for a servlet to perform an action like database access or a calculation but to not actually do any presentation. It then transfer the control to another resource.
  • Here is an example of the flow of this transfer:

Transferring Control

  • Forward – Server-side
  • Redirect – HTTP and Browser

Forwarding

  • Servlet or JSP uses the RequestDispatcher to transfer control.
  • Control is transferred entirely on the server. No network traffic is inolved.
  • The user does not see the address of the destination JSP page.

  • Code to transfer with a forward:
    String url = "/transferDemo.jsp";
    
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
    dispatcher.forward(request, response);
    

Redirection

  • Servlet use HTTP to transfer control.
  • Control is transferred by sending the client a 302 status code and a Location response header.
  • The transfer requires additional network traffic.
  • The user sees the address of the destination page and can bookmark it.

  • Code to transfer with a redirection:
    String url = "/transferDemo.jsp";
    response.sendRedirect(url);
    

Examples:

JSP Page

Forwarding Servlet

Redirection Servlet