SpringBoot项目中,cookie的设置与销毁

Posted 寻找梦想的大熊

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot项目中,cookie的设置与销毁相关的知识,希望对你有一定的参考价值。

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);
    }

 

以上是关于SpringBoot项目中,cookie的设置与销毁的主要内容,如果未能解决你的问题,请参考以下文章

springboot跨域请求设置,且允许js请求携带cookies

将cookie设置为安全时Spring Boot无法登录

SpringBoot web&基本请求处理

Springboot应用中设置Cookie的SameSite属性

springboot 1.5.x 使用tomcat8设置cookie的domain以dot开头报错

SpringBoot 一篇搞定(Cookie Session 跳转 内容协商 converter解析器 thymeleaf)