如何能在 服务端使用 Cookie 呢?

本文详细介绍如何在Spring框架中设置和读取Cookie。包括设置带有过期时间的Cookie、通过@CookieValue注解获取特定Cookie值以及读取所有Cookie值的方法。

1)设置cookie返回给客户端

@GetMapping("/change-username")
 public String setCookie(HttpServletResponse response) {
     // 创建一个 cookie
     Cookie cookie = new Cookie("username", "Jovan");
     //设置 cookie过期时间
     cookie.setMaxAge(7 * 24 * 60 * 60); // expires in 7 days
     //添加到 response 中
     response.addCookie(cookie);
 
    return "Username is changed!";
}

2)使用Spring框架提供的@CookieValue注解获取特定的 cookie的值

@GetMapping("/")
public String readCookie(@CookieValue(value = "username", defaultValue = "Atta") String username) {
    return "Hey! My username is " + username;
}

3)读取所有的 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";
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值