【问题标题】:Cookies not being set in Spring没有在 Spring 中设置 Cookie
【发布时间】:2020-10-04 10:01:17
【问题描述】:

所以我在后端编写了一段代码,通过 HttpServletResponse 设置 cookie。但是,无论我做什么,cookie 都不会存储在浏览器中。

我试过了-

  1. 将所有内容设置为 127.0.0.1
  2. 将 /etc/hosts 设置为二级域
  3. 在获取请求中设置凭据
  4. 设置 cookie 的最大期限
  5. SO 推荐的其他答案

这里是 index.html

<html>
    <head>
        <title>Cookie Test</title>
    </head>
    <body>
        <script>

            async function getCookie() {

                let response = await fetch("http://127.0.0.1:8080/getCookie");
                let data = await response.text();
                console.log(data);
            }


            getCookie();
        </script>
    </body>
</html>

这是我的控制器-


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@CrossOrigin(origins="*")
public class Controller {
    @GetMapping("/getCookie")
    public String getCookie(HttpServletResponse response) {
        Cookie cookie = new Cookie("name", "Test123");
        cookie.setPath("/");
        response.addCookie(cookie);

        return "Cookie added";

    }



}

请求被发送,没有错误。但是,每当我检查 cookie 时,它​​从未设置过。我也尝试了其他 SO 问题/答案所推荐的方法,但没有任何效果。此外,当我访问 Spring/controller 页面本身而不是 Apache/index.html 页面时,cookie 被设置。但是,当访问 Apache/index.html 页面时,cookie 没有设置。

【问题讨论】:

    标签: javascript spring spring-boot spring-mvc cookies


    【解决方案1】:

    你可以试试下面的代码。 此代码用于设置 cookie

    Cookie cookie = new Cookie("name", "Test123");
    cookie.setComment("nm"); //optional
    cookie.setMaxAge(3600); // sets the cookie expiration, ie. 1hr.
    cookie.setPath("/");
    cookie.setHttpOnly(true);
    cookie.setSecure(true);
    response.addCookie(cookie);
    

    【讨论】:

    • 这仍然不起作用,尝试在服务器端访问时cookie值为null。
    猜你喜欢
    • 2011-11-16
    • 2011-05-04
    • 1970-01-01
    • 1970-01-01
    • 2014-11-07
    • 1970-01-01
    • 2016-08-17
    • 2013-07-02
    • 2021-07-03
    相关资源
    最近更新 更多