Java: Servlet/JSP Forward or Redirect

Posted on May 19, 2009

0


How to use forward

// In Java Servlet
requestDispatcher.forward("<server side relative address>");
// In JSP
<jsp:forward page=” relativeURLspec” />

How to use redirect

response.sendRedirect("<client side access-able address>");

The fundamental difference between forward and redirect is the communication with client, i.e. web browser. In redirect, the server sends a response to the client indicating a new location where the client needs to make the next request to; hence, the client will get the intended result. While in forward, instead of sending a new location, the server forwards the request to another Java Servlet/JSP in the server side and let the Java Servlet/JSP return the intended result to the client.

Forwarding

A client browser will never realize whether its request is forwarded since the forwarding happens in the server side. Forwarding is useful when it is necessary to continue processing the current request with different Java Servlet/JSP. It allows the next Java Servlet/JSP to access the same request object. It also provides a way of passing data between two Java Servlets, two JSPs as well as a Java Servlet and a JSP. This can be done by setting an attribute in Java Servlet/JSP #1 before forwarding the request to Java Servlet/JSP #2; notice that the Java Servlet/JSP #2 can get the attribute set earlier.

Redirection

In redirection, A client browser will be informed to make the request by the server; hence, the client will reach the next Java Servlet/JSP. Notice that a client browser with redirection enabled will refresh its address bar to the next Java Servlet/JSP address, which means that a redirection address must be client access-able address. This will involve a new request object sent by the client to the next Java Servlet/JSP, which also means that no attributes passing can be performed.

Tips and Tricks

Put a return; after the sendRedirect(): A JSP will keep continue processing the rest of the code even though it finds the sendRedirect() command. It will be wasteful to let it continue working since the client does not expect anything else from the JSP and goes to the redirection.

Knowing that the address bar in the client web browser will be refreshed, a debugging process will be easier in codes with many redirection compare to those with many forwarding.

Advertisements
Tagged:
Posted in: Technology