/**
* 读取所有 cookie
* 注意二、从客户端读取 Cookie 时,包括 maxAge 在内的其他属性都是不可读的,也不会被提交。浏览器提交 Cookie 时只会提交 name 与 value 属性。maxAge 属性只被浏览器用来判断 Cookie 是否过期
* @param request
* @param response
*/
@RequestMapping("/showCookies")
public void showCookies(HttpServletRequest request,HttpServletResponse response){Cookie[] cookies = request.getCookies();// 这样便可以获取一个 cookie 数组
if (null==cookies) {System.out.println("没有 cookie=========");
} else {for(Cookie cookie : cookies){System.out.println("name:"+cookie.getName()+",value:"+ cookie.getValue());
}
}
}
/**
* 添加 cookie
* @param response
* @param name
* @param value
*/
@RequestMapping("/addCookie")
public void addCookie(HttpServletResponse response,String name,String value){Cookie cookie = new Cookie(name.trim(), value.trim());
cookie.setMaxAge(30 * 60);// 设置为 30min
cookie.setPath("/");
System.out.println("已添加 ===============");
response.addCookie(cookie);
}
/**
* 修改 cookie
* @param request
* @param response
* @param name
* @param value
* 注意一、修改、删除 Cookie 时,新建的 Cookie 除 value、maxAge 之外的所有属性,例如 name、path、domain 等,都要与原 Cookie 完全一样。否则,浏览器将视为两个不同的 Cookie 不予覆盖,导致修改、删除失败。*/
@RequestMapping("/editCookie")
public void editCookie(HttpServletRequest request,HttpServletResponse response,String name,String value){Cookie[] cookies = request.getCookies();
if (null==cookies) {System.out.println("没有 cookie==============");
} else {for(Cookie cookie : cookies){if(cookie.getName().equals(name)){System.out.println("原值为:"+cookie.getValue());
cookie.setValue(value);
cookie.setPath("/");
cookie.setMaxAge(30 * 60);// 设置为 30min
System.out.println("被修改的 cookie 名字为:"+cookie.getName()+", 新值为:"+cookie.getValue());
response.addCookie(cookie);
break;
}
}
}
}
/**
* 删除 cookie
* @param request
* @param response
* @param name
*/
@RequestMapping("/delCookie")
public void delCookie(HttpServletRequest request,HttpServletResponse response,String name){Cookie[] cookies = request.getCookies();
if (null==cookies) {System.out.println("没有 cookie==============");
} else {for(Cookie cookie : cookies){if(cookie.getName().equals(name)){cookie.setValue(null);
cookie.setMaxAge(0);// 立即销毁 cookie
cookie.setPath("/");
System.out.println("被删除的 cookie 名字为:"+cookie.getName());
response.addCookie(cookie);
break;
}
}
}
}
/**
* 根据名字获取 cookie
* @param request
* @param name cookie 名字
* @return
*/
public Cookie getCookieByName(HttpServletRequest request,String name){Map<String,Cookie> cookieMap = ReadCookieMap(request);
if(cookieMap.containsKey(name)){Cookie cookie = (Cookie)cookieMap.get(name);
return cookie;
}else{return null;}
}
/**
* 将 cookie 封装到 Map 里面
* @param request
* @return
*/
private Map<String,Cookie> ReadCookieMap(HttpServletRequest request){Map<String,Cookie> cookieMap = new HashMap<String,Cookie>();
Cookie[] cookies = request.getCookies();
if(null!=cookies){for(Cookie cookie : cookies){cookieMap.put(cookie.getName(), cookie);
}
}
return cookieMap;
}