JavaEE implements request redirection through response

  • 2020-04-01 03:32:22
  • OfStack

  Request redirection is when a web resource receives a request from a client and notifies the client to access another web resource. This is called request redirection. The 302 status code and the location header can be redirected.

  The most common application scenario for request redirection is user login. The following sample code redirects from another page to the user login page:


 package com.yyz.response;
 import java.io.IOException;
 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 public class ResponseDemo extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
             throws ServletException, IOException {
         response.setHeader("location", "/day06/register.html");
         response.setStatus(302);
         //The two sentences above are equivalent to the following:
         //response.sendRedirect("/day06/register.html");
 }
     public void doPost(HttpServletRequest request, HttpServletResponse response)
             throws ServletException, IOException {
            doGet(request,response);
     }
 }

  Two notable features of request redirection: 1. Two requests were sent to the server. 2. The address bar has changed. Because an important principle of server optimization is to reduce the number of requests sent, use less request redirection.


Related articles: