Sendredirect In Servlet
In this section you will read about the sendredirect() method.
sendredirect() method is used to redirect the control to the different server or to another web resources within the same server. sendredirect() method is declared in the javax.servlet.http.HttpServletResponse. When this method is used to redirect the control to different server or domain a new request is initiated by the browser for the given URL and the old request and response object is lost. This is because, all this process is done by the browser because the container assigned this task to browser for transferring control. So, the redirect sends a header back to the browser/client and the header contains the URL where the browser has to be redirected that's why the old request and response is lost.
Method's Syntax
void sendRedirect(java.lang.String location) : This method transfer the control to different server or another web resources within the same server with the specified location and clears the buffer.
Example
Here we will give a simple example which will demonstrate you about how we can use the sendredirect() method and can transfer the control from one resource to another. In this example we will create a simple Servlet and we will use the sendredirect() method of HttpServletResponse. Here you will see how the control is transferred from one server/domain to different server/domain.
SendRedirectExample.java
package net.roseindia; import java.io.*; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServlet; public class SendRedirectExample extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); response.sendRedirect("http://www.Google.com"); } }
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>sendredirect</display-name> <servlet> <servlet-name>redirect</servlet-name> <servlet-class>net.roseindia.SendRedirectExample</servlet-class> </servlet> <servlet-mapping> <servlet-name>redirect</servlet-name> <url-pattern>/locate</url-pattern> </servlet-mapping> </web-app>
Output
When you will compile and deploy this example and uses the localhost:8181/sendredirect/locate URL at the browser's address bar you will see that the control is transferring to the http://www.Google.com page which is located in the different server.