設置 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!";
}
使用 Spring 框架提供的 @CookieValue
註解獲取特定的 cookie 的值
@GetMapping("/")
public String readCookie(@CookieValue(value = "username", defaultValue = "Atta") String username) {
return "Hey! My username is " + username;
}
讀取所有的 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";
}