Send redirect in servlet

sendRedirect() is present inside the HttpServletResponse interface and redirects the response to another resource. As per Servlet doc, sendRedirect() sends a temporary redirect response to the client using the specified redirect location URL and clears the buffer. The buffer will be replaced with the data set by this method. Calling this method sets the status code to SC_FOUND 302 (Found). This method can accept relative URLs;the servlet container must convert the relative URL to an absolute URL before sending the response to the client. If the location is relative without a leading '/' the container interprets it as relative to the current request URI. If the location is relative with a leading '/' the container interprets it as relative to the servlet container root.

if the response has already been committed, this method throws an IllegalStateException.

Example of sendRedirect in servlet :-

send-redirect-in-servlet


Difference Between sendRedirect() and Foward() :-

foward() method of RequestDispatcher interface
RequestDispatcher dispatcher=req.getRequestDispatcher("xxxx.jsp");
dispatcher.forward(req, resp);

1. The request is transfer to other resource within same server.

2. The request is shared by the target resource..

3. We cannot see forwarded message(URL is not visible to end user), it is transparent.

4. The forward() method is faster than sendRedirect() method because forward() method includes once cycle only.

5. It is declared in RequestDispatcher interface.


sendRedirect() method of HttpServletRequest interface :
1. The request is transfer to other resource to different server(external url).

2. The sendRedirect() method is provided under HTTP so it can be used only with HTTP clients.

3.Two request and response calls are consumed.

4. It can be used within and outside the server.

5. We can see redirected address, it is not transparent.

6. The sendRedirect() method is slower because when new request is created old request object is lost.

7. It is declared in HttpServletResponse.