重定向是服務器通知瀏覽器去訪問另一個地址,即再發出另一個請求。
如果要重定向的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()輸出數據,不然可能會出現異常;
- 用重定向技術,瀏覽器地址欄會發生變化。用戶登錄和顯示購物車時,通常會用到重定向技術。