Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Servlet page redirects


May 15, 2021 Servlet


Table of contents


Servlet page redirects

When the document moves to a new location, we need to send this new location to the client, we need to use page redirection. Of course, it may also be for load balancing, or just for simple randomness, all of which may result in web page redirection.

The easiest way to redirect a request to another page is to use the sendRedirect() method of the response object. H ere's the definition of the method: The easiest way to redirect a request to another page is to use the method's endingRedirect() response object. Here's how to define it:

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 = "http://www.newpage.com" ;
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site); 
....

This example shows how the servlet redirects the page to another location:

import java.io.*;
import java.sql.Date;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class PageRedirect extends HttpServlet{
    
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
      // 设置响应内容类型
      response.setContentType("text/html");

      // 要重定向的新位置
      String site = new String("http://www.w3cschool.cn");

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

Now let's compile the servlet above and create the following entry .xml the web server file:

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

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

Now call this servlet http://localhost:8080/PageRedirect the URL and the url. This will take you to a given URL http://www.w3cschool.cn.