cookie的设置与销毁
1.设置cookie
/** * 设置一个cookie * @param response HttpServletResponse * @param name cookie的名称 * @param value cookie的内容 * @param maxAge cookie的持续时间 */ public static void set(HttpServletResponse response, String name, String value, int maxAge) { Cookie cookie = new Cookie(name, value); cookie.setPath("/"); cookie.setMaxAge(maxAge); response.addCookie(cookie); }
2.销毁cookie(将cookie的持续时间设置为0)
2.1查找cookie
/** * 查找cookie * @param request HttpServletRequest * @param name 要查找的cookie的名称 * @return */ public static Cookie get(HttpServletRequest request, String name) { //1.将cookies放到map中去 Map<String, Cookie> cookieMap = new HashMap<>(); Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { cookieMap.put(cookie.getName(), cookie); } } //2.查找是否存在cookie,是则返回查找到的cookie if (cookieMap.containsKey(name)) { return cookieMap.get(name); } else { return null; } }
2.2销毁cookie
CookieUtil.set(response, CookieConstant.TOKEN, null, 0);
3.实际运用效果
生成cookie
@PostMapping("/login") public ModelAndView login(@RequestParam("openid") String openid, Map<String, Object> map, HttpServletResponse response) { //设置token到cookie set(response, CookieConstant.TOKEN, token, CookieConstant.EXPORE); //页面跳转 return new ModelAndView("redirect:" + projectUrlConfig.getSell() + "/sell/seller/order/list"); }
注销cookie
@GetMapping("/logout") public ModelAndView logout(HttpServletRequest request, HttpServletResponse response, Map<String, Object> map) { //1.从cookie里面查询 Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN); if (cookie != null) { //清除cookie,设置过期时间为0 CookieUtil.set(response, CookieConstant.TOKEN, null, 0); } map.put("msg",ResultEnum.LOGOUT_SUCCESS.getMessage()); map.put("url","/sell/seller/toLogin"); return new ModelAndView("common/success",map); }