Servlet web page redirection


Release date:2023-12-15 Update date:2023-12-15 Editor:admin View counts:98

Label:

Servlet web page redirection

When the document is moved to a new location and we need to send this new location to the client, we need to use web page redirection. Of course, it may also be for load balancing, or just for simple random, all of which may involve web redirection.

The easiest way to redirect a request to another web page is to use the response object’s sendRedirect() method. The following is the definition of the 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 web page location. You can also do this by putting setStatus() and setHeader() method to achieve the same effect:

....
String site = "http://www.runoob.com" ;
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site);
....

Example

This example shows how Servlet redirects the page 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
      String site = new String("http://www.runoob.com");

      response.setStatus(response.SC_MOVED_TEMPORARILY);
      response.setHeader("Location", site);
    }
}

Now let’s compile the Servlet above, and in the web.xml create the following entries in the file:

....
 <servlet>
     <servlet-name>PageRedirect</servlet-name>
     <servlet-class>PageRedirect</servlet-class>
 </servlet>

 <servlet-mapping>
     <servlet-name>PageRedirect</servlet-name>
     <url-pattern>/TomcatTest/PageRedirect</url-pattern>
 </servlet-mapping>
....

Now call this Servlet by accessing URL http://localhost:8080/PageRedirect. This will take you to the given URL http://www.runoob.com.

Powered by TorCMS (https://github.com/bukun/TorCMS).