重定向是服务器通知浏览器去访问另一个地址,即再发出另一个请求。
如果要重定向的URL是在同一个服务器内,那么可以使用相对路径,例如:
public class AServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.sendRedirect("/hello/BServlet");
}
}
重定向的URL地址为:http://localhost:8080/hello/BServlet。
重定向小结:
- 重定向是两次请求;
- 重定向的URL可以是其他应用,不局限于当前应用;
- 重定向的响应头为302,并且必须要有Location响应头;
- 重定向就不要再使用response.getWriter()或response.getOutputStream()输出数据,不然可能会出现异常;
- 用重定向技术,浏览器地址栏会发生变化。用户登录和显示购物车时,通常会用到重定向技术。