response.sendRedirect(URL地址)
重定向响应会在响应头中添加一个Location的key对应的value是给定的URL。客户端浏览器在解析响应头后自动向Location中的URL发送请求。
重定向响应特点:
- 重定向会产生两次请求两次响应。
- 重定向的URL是由客户端浏览器发送的。
浏览器地址栏会有变化。
public class RedirectServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//产生重定向响应
resp.sendRedirect("https://www.baidu.com");
}
}