sendRedirect in Servlet

In the previous article, we have discussed RequestDispatcher which dispatches the request from one page to another page or servlet. But if we want to take a response from one page to another what we will use. So in this case we have the sendRedirect method in servlet. In this article, we will discuss the sendRedirect() method.

What is sendRedirect?

The sendRedirect() method is of  HttpServletResponse Interface.This method is used to take responses from one page to another.sendRedirect() method can go for resources inside or outside the resources.

Let’s see the Example for sendRedirect() method in Servlet

In this example client request the server a query and it redirects it to https://codedec.com/ page.

index.html

SendRedirectExample.java

web.xml

Output

Difference between forward() method and sendRedirect() method

 

forward() sendRedirect()
It works on the server-side. It works on both inside or outside servers.
It sends the same request and response It always sends new requests.
It can be used if you want to transfer control to the same domain It can be used if you want to transfer control to another domain.
request.getRequestDispatcher(“index.html”).

forward(request,response);

response.sendRedirect(“index.html”);