兴趣爱好Javajava学习笔记-web基础九(cookie)
执笔 介绍
创建cookie
/创建cookie.png)
1 2 3 4 5 6 7 8 9 10 11 12 13
| protected void createCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Cookie cookie = new Cookie("key1", "value1"); resp.addCookie(cookie);
Cookie cookie1 = new Cookie("key2", "value2"); resp.addCookie(cookie1);
resp.getWriter().write("Cookie创建成功"); }
|
获取cookie
/获取cookie.png)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| protected void getCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Cookie[] cookies = req.getCookies(); for (Cookie cookie : cookies) { if ("key1".equals(cookie.getName()) ){ resp.getWriter().write(cookie.getName() + "=" + cookie.getValue() + "<br/>"); break; } } Cookie newCookie = CookieUtils.findCookie("key1",cookies); if (newCookie != null) { resp.getWriter().write(newCookie.getName() + "=" + newCookie.getValue() + "<br/>"); } resp.getWriter().write("Cookie获取成功"); }
|
utils:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| public class CookieUtils {
public static Cookie findCookie(String name, Cookie[] cookies){ if (name == null || cookies.length == 0 || cookies == null) { return null; } for (Cookie cookie : cookies) { if (name.equals(cookie.getName())){ return cookie; } } return null; } }
|
cookie修改
方案一
1 2 3 4 5 6
| 方案一:
Cookie cookie = new Cookie("key1","newValue1");
resp.addCookie(cookie);
|
方案二
1 2 3 4 5 6 7 8 9
| 方案二:
Cookie cookie = CookieUtils.findCookie("key2", req.getCookies()); if (cookie != null) {
cookie.setValue("newValue2");
resp.addCookie(cookie); }
|
生命周期
satMaxAge()
- 正数,表示在指定的秒数后过期
- 负数,表示浏览器一关,Cookie 就会被删除(默认值是-1)
- 零,表示马上删除 Cookie
有效路径path的设置
1 2 3 4 5 6 7 8 9
| CookieA path=/工程路径 CookieB path=/工程路径/abc 请求地址如下: http://ip:port/工程路径/a.html CookieA 发送 CookieB 不发送 http://ip:port/工程路径/abc/a.html CookieA 发送 CookieB 发送
|