------------------------------- cookie的路徑-------------------------------------
Cookie的路徑
Cookie還有一個path屬性,可以通過Cookie#setPath(String)方法來設定。你可以使用HttpWatch檢視響應中的Set-Cookie中是否存在路徑。下面是通過FireFox檢視Cookie資訊。
也就是說,就算你不設定Cookie的path,Cookie也是有路徑的。這個路徑就是請求的路徑。例如在請求http://localhost/day07_03/AServlet時,伺服器響應了一個Cookie,那麼這個Cookie的預設路徑就是/day07_03/。
例如請求的路徑是http://localhost/day07_03/servlet/BServlet時,伺服器響應了一個Cookie,那麼這個Cookie的預設路徑就是/day07_03/servlet/。
到現在我們還沒說過Cookie的path有什麼用,現在我們來聊聊path的作用。首先聲明一點,path不是指Cookie在用戶端存放的路徑!!!不同的浏覽器存放Cookie的路徑是不同的!!!你不能通過Cookie的path來指定Cookie檔案的存放路徑!!!
那麼Cookie的path是幹什麼的呢?假設你的浏覽器目前已經有了兩個Cookie:
- c1:name=id; value=itcast; path=/day07_03/;
- c2:name=name; value=qdmmy6; path=/day07_03/servlet/。
當通路http://localhost/day07_03/*時,請求頭中會包含c1,而不會包含c2。
當通路http://localhost/day07_03/servlet/*時,請求頭中會包含c1和c2。
也就是說,在通路子路徑時,會包含其父路徑的Cookie,而在通路父路徑時,不包含子路徑的Cookie。
如果你想在BServlet中設定的Cookie,在用戶端通路AServlet時也包含在請求頭中,那麼就需要設定BServlet中的Cookie的path:
- c2.setPath(“/day07_03/”):寫死;
- c2.setPath(request.getContextpath() + “/”):活編碼。
這樣就可以設定Cookie的路徑,儲存在通路AServlet時,也會包含BServlet中添加的Cookie。
Cookie的SetPath設定cookie的路徑,這個路徑直接決定伺服器的請求是否會從浏覽器中加載某些cookie。
首先預設情況如果不設定cookie的path,預設是 /項目名稱/目前路徑的上一層位址如:請求路徑:/cookie_demo/servlet/login, cookie的路徑:/cookie_demo/servlet
如果我們設定path,如果目前通路的路徑包含了cookie的路徑(目前通路路徑在cookie路徑基礎上要比cookie的範圍小)cookie就會加載到request對象之中。
代碼示例:
public class RegistServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); //擷取使用者名和密碼 String username = request.getParameter("username"); String password = request.getParameter("password"); username = "likunpeng"; password = "123"; System.out.println("使用者名:"+username); System.out.println("密碼:"+password); //建立3個cookie對象,将使用者名和密碼連接配接存儲,使用逗号分開 Cookie cookie = new Cookie("userpass", username+","+password); Cookie cookie1 = new Cookie("userpass", username+"1,"+password); Cookie cookie2 = new Cookie("userpass", username+"2,"+password); //設定cookie的存活時間 cookie.setMaxAge(60*10); cookie1.setMaxAge(60*10); cookie2.setMaxAge(60*10); //設定cookie的path路徑 cookie.setPath("/cookie_demo3/"); cookie1.setPath("/cookie_demo3/a/"); cookie2.setPath("/cookie_demo3/a/b/"); //把cookie寫入浏覽器 response.addCookie(cookie); response.addCookie(cookie1); response.addCookie(cookie2); response.getWriter().print("<h1>success</h1>"); } } |