【问题标题】:Clear Cookies in Spring Boot WebFlux在 Spring Boot WebFlux 中清除 Cookie
【发布时间】:2021-11-05 09:51:45
【问题描述】:

当我从我的应用程序中注销时,我正在尝试删除所有 cookie。我可以为 Spring Boot Web 项目执行如下操作。

/**
     * Clears all the cookies from the response
     *
     * @param req
     * @param resp
     */
    public static void deleteCookies(HttpServletRequest req, HttpServletResponse resp) {
        Cookie[] cookies = req.getCookies();
        if (cookies != null) {
            for (Cookie cookieToBeDeleted : cookies) {
                logger.debug("Deleting cookie: {} having value: {}", cookieToBeDeleted.getName(),
                        cookieToBeDeleted.getValue());
                cookieToBeDeleted.setMaxAge(0);
                resp.addCookie(cookieToBeDeleted);
            }
        }
    }

但是对于 webflux 来说同样是棘手的。我们有 org.springframework.http.server.reactive.ServerHttpRequest 而不是 HttpServletRequest。我们这里有一个 multimap,而不是 cookie 数组。

 private void deleteCookies(ServerHttpRequest request, ServerHttpResponse response) {
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();

        for (Entry<String, List<HttpCookie>> cookie : cookies.entrySet()) {
            log.debug(cookie.toString());
        }

        log.debug("Response cookies" + response.getCookies().toString());

    }

spring webflux 高手可以帮我实现这里的逻辑吗?

【问题讨论】:

    标签: java spring-boot cookies spring-webflux servlet-3.0


    【解决方案1】:

    能够删除 webflux 的 cookie。

    /**
         * Clears all the cookies from the response
         *
         * @param request
         * @param response
         */
        public void deleteCookies(ServerHttpRequest request, ServerHttpResponse response) {
            MultiValueMap<String, HttpCookie> cookies = request.getCookies();
    
            for (Entry<String, List<HttpCookie>> cookie : cookies.entrySet()) {
                for (HttpCookie cookieToBeDeleted : cookie.getValue()) {
                    log.debug("Deleting cookie: {} having value: {}", cookieToBeDeleted.getName(), cookieToBeDeleted
                            .getValue());
                    response.addCookie(ResponseCookie.from(cookieToBeDeleted.getName(), cookieToBeDeleted.getValue())
                            .maxAge(0).build());
                }
            }
    
            log.debug("Response cookies" + response.getCookies().toString());
    
        }
    
    

    【讨论】:

      猜你喜欢
      • 2018-08-24
      • 2021-06-17
      • 2020-05-26
      • 2020-02-09
      • 2021-11-20
      • 2018-10-11
      • 1970-01-01
      • 2020-05-04
      • 2019-09-19
      相关资源
      最近更新 更多