【问题标题】:Can not get cookie value in Spring boot在 Spring Boot 中无法获取 cookie 值
【发布时间】:2020-06-10 00:19:09
【问题描述】:

当用户登录时,我使用 Javascript 将 JWT 令牌保存在 cookie 中

document.cookie = "token=Bearer " + userDetails.loginSuccess.token;

但是当我向 Spring Boot Controller 发出请求时,我找不到 cookie

 public String home(@CookieValue(value = "token") String token,
                    @PathVariable String businessId,
                    @PathVariable String cartId, ModelMap model,
                    HttpServletRequest request) {}

如何在 Controller 中获取 cookie 值?

【问题讨论】:

    标签: javascript spring-boot cookies


    【解决方案1】:

    可以直接在控制器中获取HTTPServletRequest对象,然后像这样获取cookies。

     public ResponseEntity<String> home(
      HttpServletRequest request,
      HttpServletResponse response,
      @RequestBody Map<String, String> params) {
          request.getCookies();
      }
    

    【讨论】:

      【解决方案2】:

      应该是 name="token" 而不是 value

      public String home(@CookieValue(name = "token") String token,
                          @PathVariable String businessId,
                          @PathVariable String cartId, ModelMap model,
                          HttpServletRequest request) {}
      

      【讨论】:

      • name 和 token 是彼此的别名,因此可以互换。
      猜你喜欢
      • 2021-06-14
      • 1970-01-01
      • 2018-01-25
      • 2020-07-13
      • 2022-07-14
      • 1970-01-01
      • 2021-05-12
      • 2018-07-04
      • 1970-01-01
      相关资源
      最近更新 更多