Cookie的作用域

本文详细介绍了如何在SpringBoot中使用Cookie进行数据保存,包括设置Cookie的有效期、安全性和可见性,以及如何读取和获取所有Cookie。同时对比了Cookie与Session的区别,前者在客户端保存数据,后者在服务端保存数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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会对调用端隐藏

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值