Servlet Page Redirect
# Servlet Page Redirect
When a document moves to a new location, we need to send this new location to the client, and we need to use page redirection. Of course, it could also be for load balancing, or just for simple randomness; page redirection can be used in all these situations.
The simplest way to redirect a request to another page is to use the `sendRedirect()` method of the response object. Here 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 the status code and the new page location. You can also achieve the same effect by using the `setStatus()` and `setHeader()` methods together:
....String site = "https://example.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.tutorial.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 be redirected String site = new String("https://example.com"); response.setStatus(response.SC_MOVED_TEMPORARILY); response.setHeader("Location", site); }}
Now let us compile the above Servlet and create the following entry in the web.xml file:
.... PageRedirect PageRedirect PageRedirect /TomcatTest/PageRedirect ....
Now call this Servlet by accessing the URL http://localhost:8080/PageRedirect. This will take you to the given URL https://example.com.
YouTip