请求重定向指的是一个web资源收到客户端请求后,通知客户端去访问另外一个web资源,这称之为请求重定向。302状态码和location头即可实现重定向。
请求重定向最常见的应用场景就是用户登录。 下面的示例代码从另一个页面重定向到用户登录页面:
复制代码代码如下:
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);
//上面两句代码等同于下面这句代码:
//response.sendRedirect("/day06/register.html");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,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);
//上面两句代码等同于下面这句代码:
//response.sendRedirect("/day06/register.html");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}
请求重定向的两个显著的特点:1.向服务器发送了两次请求。2.地址栏发生改变。由于服务器优化的一个重要原则是减少请求发送的次数,因而要少用请求重定向。