為什麼重定向是響應,轉發和包含是請求,以及他們之間的區別
阿新 • • 發佈:2018-11-05
總結一:
重定向:是伺服器對客戶端做出的響應,讓客戶端重新請求request面
轉 發:轉發是伺服器去自己去請求新的頁面,而不做出響應,做出響應應該是新頁面的事情
總結二
什麼時候用重定向(sendRedirect),什麼時候用轉發(forward),什麼時候用包含(include)
重定向:會重新請求一次,所以位址列會顯示重新請求的地址,而且
request和response都會重新生成
轉 發:只是伺服器內轉發,位址列還是i顯示請求的地址,並且requset和response資料還在,但是體內資訊不存在了,也就是響應資料
包 含:和轉發一樣,但是響應資料還在
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
if (username.equals("ouyang")){
HttpSession httpSession = request.getSession();
httpSession.setAttribute("username",username);
response.sendRedirect("/welcome.jsp");
}else{
request.setAttribute("warn","登陸失敗,請重新登陸");
request.getRequestDispatcher("/login.jsp" ).forward(request,response);
}
response.getWriter().println("123");
}