春季未设置Cookie

时间:2020-06-15 02:56:19

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

因此,我在后端编写了一段代码,该代码通过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。

1 个答案:

答案 0 :(得分:0)

您可以尝试以下代码。 此代码设置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);