Servlet Cookie & Session
阿新 • • 發佈:2018-12-06
Cookie
使用Servlet中的Cookie類即可。
設定cookie
設定cookie是通過response物件發給客戶端。
Cookie cookie_1 = new Cookie("key", "value"); // cookie不設定過期時間(臨時cookie),預設在瀏覽器視窗關閉之前有效。 Cookie cookie_2 = new Cookie("aaa", "bbbbb"); // 設定cookie的過期時間,單位為秒,0表示刪除該cookie。 cookie_2.setMaxAge(100); // 設定域名 cookie_2.setDomain("www.baidu.com"); // 使用setPath(uri), 設定cookie的有效路徑,只在指定的path下可見 cookie_2.setPath("/demo/test"); // 將cookie放入response物件中,返回給客戶端。 resp.addCookie(cookie_1); resp.addCookie(cookie_2);
獲取cookie
獲取cookie時,是從request物件中獲取的。
public class TestgetCookie extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Cookie[] cookies = req.getCookies(); if (cookies != null) { for (Cookie c : cookies) { System.out.println(c.getName() + "=" + c.getValue()); } } // 如果要獲取某一個cookie物件key對應的value,需要遍歷一次Cookie[],封裝一下。 String value = getCookieValue(cookies, "key"); System.out.println(value); } /** * 獲取cookie中某一項的值 */ public static String getCookieValue(Cookie[] cookie, String key) { if (cookie != null && key != null) { for (Cookie c : cookie) { if (c.getName().equals(key)) { return c.getValue(); } } } return null; } }