Servlet – sendRedirect() Method with Example
Servlets are the Java programs that run on the server-side and generate dynamic responses to the client request. Servlet accepts the request from the browser, processes it, and generates the response to the browser. While processing the request, let’s say if need to call another servlet from a different server, we need to redirect the response to that resource. To achieve this, Java servlets provide sendRedirect() method in HttpServletResponse interface in javax.servlet.http package. To understand better, let’s look at some real-time examples.
Example 1: Nowadays, there are so many online shopping sites, where we can purchase goods. Once we select the product, are ready to purchase, and click on pay, the browser will redirect to the respective online payment page. Here, the response from the shopping website redirects it to the payment page and a new URL can be seen in the browser.
Example 2: In some online education applications, if we want to include a google search operation or to include a link to another website for more information on the topic, we need to redirect the response to the specific URL.
HttpServletResponse extends the ServletResponse interface to provide functionality specific to HTTP requests and responses. It provides methods to access HTTP headers and cookies.
public interface HttpServletResponse extends ServletResponse
sendRedirect() method redirects the response to another resource, inside or outside the server. It makes the client/browser to create a new request to get to the resource. It sends a temporary redirect response to the client using the specified redirect location URL.
void sendRedirect(java.lang.String location) throws java.io.IOException
- sendRedirect() accepts the respective URL to which the request is to be redirected.
- Can redirect the request to another resource like Servlet, HTML page, or JSP page that are inside or outside the server.
- It works on the HTTP response object and always sends a new request for the object.
- A new URL that is being redirected can be seen in the browser.
As we discussed above, we will create a simple servlet that will redirect the page to another website.
We have a form with action =”redirect” method = “get”, so Index.html maps the servlet having ‘/redirect’ URL and execthe ‘doGet’ method in it.
We need to import all the required packages from javax.servlet. Instead of mapping the page with servlet in web.xml, we are specifying it using annotation – @WebServlet(“/redirect”). When the ‘doGet’ method executes, the response will redirect to the specified URL.
Run the Index.html on the server, the below page will be displayed.
When clicking for more information, we specified redirecting the response to that particular URL.
This way, we can use the sendRedirect() method in Servlets.