本文直接展示servlet的測試結果。
servlet的代碼中使用sendRedirect:
public class SessionTest extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
...
response.sendRedirect("http://localhost:8080/web/");
...}
查看瀏覽器交互過程,先是請求該servlet:
-
Request URL:http://localhost:8080/web/SessionTest
-
Request Method:GET
-
Status Code:302 Found
可以看到response返回了302,並帶上了location, 指示瀏覽器做第二次跳轉請求,瀏覽器得到提示後進行第二次請求。
同樣的servlet,將代碼改爲forward,實現了在servlet容器內部的跳轉,對瀏覽器實際上是不可見得。
request.getRequestDispatcher("/index.jsp").forward(request, response);
看一下tomcat服務器的響應,一個200 OK之後,直接返回了內容,很直接
-
Request URL:http://localhost:8080/web/SessionTest
-
Request Method:GET
-
Status Code:200 OK
再看cookie的保存,將以上代碼改爲將cookie加入response:
Cookie cookie = new Cookie("test","test");
response.addCookie(cookie);
PrintWriter out = response.getWriter();
再看HTTP head:
-
Request URL:http://localhost:8080/web/SessionTest
-
Request Method:GET
-
Status Code:200 OK
Tomcat通過HTTP協議的Set-Cookie將servlet的cookie放入了響應頭,查看瀏覽器的cookie,除了jsessionid,又加了一個test/test的cookie進來。