Request redirection means that after a web resource receives a client request, it notifies the client to access another web resource. This is called request redirection. The 302 status code and location header can be used to implement redirection.
The most common application scenario for request redirection is user login. The following sample code redirects to the user login page from another page:
Copy the code code as follows:
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 above two sentences of code are equivalent to the following code:
//response.sendRedirect("/day06/register.html");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}
There are two notable features of request redirection: 1. Two requests are sent to the server. 2. The address bar changes. Since an important principle of server optimization is to reduce the number of requests sent, request redirection should be used sparingly.