Servlet Web Page Redirect
When a document moves to a new location and we need to send this new location to the client, we need to use a web page redirect. Of course, it may also be for load balancing, or just for simple randomness; web page redirects can be used in all these situations.
The simplest way to redirect a request to another web page is to use the sendRedirect() method of the response object. The following is the definition of this method:
public void HttpServletResponse.sendRedirect(String location)
throws IOException
This method sends the response back to the browser along with a status code and the new web page location. You can also achieve the same effect by using the setStatus() and setHeader() methods together:
....
String site = "http://www.runoob.com" ;
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site);
....
Example
This example shows how a Servlet performs a page redirect to another location:
package com.runoob.test;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class PageRedirect
*/
@WebServlet("/PageRedirect")
public class PageRedirect extends HttpServlet{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html;charset=UTF-8");
// New location to redirect to
String site = new String("http://www.runoob.com");
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site);
}
}
Now let's compile the above Servlet and create the following entry in the web.xml file:
....
PageRedirect
PageRedirect
PageRedirect
/TomcatTest/PageRedirect
....
Now invoke this Servlet by visiting the URL http://localhost:8080/PageRedirect. This will redirect you to the given URL http://www.runoob.com.