Cookie 是在客户端保存数据,Session 在服务端保存数据
Spring Boot写cookie
@GetMapping("/set")
public String setCookie(HttpServletResponse response) {
// create a cookie
Cookie cookie = new Cookie("username", "Jovan");
// If no expiration time is specified for a cookie, it lasts as long as the session is not expired.
cookie.setMaxAge(7 * 24 * 60 * 60); // expires in 7 days
// A secure cookie is the one that is only sent to the server over an encrypted HTTPS connection.
// Secure cookies cannot be transmitted to the server over unencrypted HTTP connections.
cookie.setSecure(true);
// 设置了这个为true表示对客户端不可见
cookie.setHttpOnly(true);
//add cookie to response
response.addCookie(cookie);
return "Username is changed!";
}
Spring boot 获取cookie
@GetMapping("/get")
public String readCookie(@CookieValue(value = "username", defaultValue = "Atta") String username) {
return "Hey! My username is " + username;
}
Spring boot 获取所有cookie
@GetMapping("/all-cookies")
public String readAllCookies(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
return Arrays.stream(cookies)
.map(c -> c.getName() + "=" + c.getValue()).collect(Collectors.joining(", "));
}
return "No cookies";
}
以上内容来自https://attacomsian.com/blog/cookies-spring-boot
HttpServletResponse response = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getResponse();
HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
Cookie tokenCookie = new Cookie(LoginChannelEnum.H5.getHeaderKey(), token);
tokenCookie.setDomain(rootDomian);
tokenCookie.setMaxAge(MAX_AGE);
tokenCookie.setPath("/");
response.addCookie(tokenCookie);
cookie的作用域
假设有三个域名 bedroom.ranran.com、bathroom.ranran.com、ranran.com,其中 bedroom.ranran.com、bathroom.ranran.com是ranran.com的子域名
1、写Cookie,如果不设定域名,那么默认写到当前域名;
两个子域名不能相互写,即在bedroom.ranran.com下不能写cookie到bathroom.ranran.com下,反之亦然;
但是三个域名都可以写到顶级域名ranran.com下;
在ranran.com域名下不能写子域名;
2、拿cookie
写在顶级域名下的cookie,顶级域名和子域名都能共享;
当cookie写到某一个子域名下,例如写在 bedroom.ranran.com下,那么
另一个子域名bathroom.ranran.com和ranran.com都拿不到这个cookie,只有bedroom.ranran.com和它的子域名能拿到改Cookie
3、当设置的过期时间超时以后cookie也会拿不到
4、设置了httpOnly后cookie会对调用端隐藏