Tuesday, 3 June 2014

Difference Between sendRedirect() and forward() in Java

     This is one of the most frequently asked Java interview questions, so it is important to prepare for it thoroughly. 

     One of the most frequently asked Servlet interview questions is the difference between sendRedirect() and forward(). Although both are used to transfer a request from one resource to another, they work in different ways.

How forward() Works

    The forward() method forwards the request from one resource (Servlet, JSP, or HTML) to another within the same web application. The control is transferred internally by the server, so the client (browser) is unaware of the forwarding.

Example

RequestDispatcher dispatcher = request.getRequestDispatcher("home.jsp");
dispatcher.forward(request, response);

Key Points

  • The browser URL remains the same.
  • Uses the same request and response objects.
  • Request attributes are preserved.
  • Faster because no additional request is sent to the server.

How sendRedirect() Works

The sendRedirect() method sends an HTTP redirect response (status code 302) to the browser. The browser then makes a new request to the specified URL.

Example

response.sendRedirect("home.jsp");

Key Points

  • The browser URL changes.
  • Creates a new request.
  • Request attributes are lost.
  • Can redirect to another application or an external website.

When to Use forward()

Use forward() when:

  • Navigating between resources within the same application.
  • You need to preserve request attributes.
  • Better performance is desired.
  • The user should not see the target resource in the browser's address bar.

When to Use sendRedirect()

Use sendRedirect() when:

  • Redirecting to another application or domain.
  • You want the browser URL to change.
  • Implementing the Post/Redirect/Get (PRG) pattern to avoid duplicate form submissions.
  • Redirecting after login, logout, or successful form submission.

Example Scenario

Suppose a user submits a login form.

Using forward()

Browser


LoginServlet


RequestDispatcher.forward()


home.jsp
  • URL remains: http://localhost:8080/login
  • Request attributes are available in home.jsp.

Using sendRedirect()

Browser


LoginServlet


response.sendRedirect("home.jsp")


Browser receives redirect


New Request


home.jsp
  • URL changes to: http://localhost:8080/home.jsp
  • A new request is created.

1 comment:

  1. Hi there, yup this piece of writing is truly good and I have learned lot of things from it concerning blogging.
    thanks.

    ReplyDelete