设置Cookie
@GetMapping("/change-username")
public String setCookie(HttpServletResponse response) {
// 创建一个 cookie对象
Cookie cookie = new Cookie("username", "Jovan");
//将cookie对象加入response响应
response.addCookie(cookie);
return "Username is changed!";
}
获取Cookie
@GetMapping(value = "/readCookies")
public void readCookies(HttpServletRequest request, HttpServletResponse response) throws IOException {
//设置contentType,解决中文乱码
response.setContentType("text/html;charset=utf-8");
PrintWriter writer = response.getWriter();
Cookie[] cookies = request.getCookies();
if (cookies == null) {
writer.println("从request中未读取到cookie");
} else {
writer.println("cookie数量: " + cookies.length);
for (Cookie aCookie : cookies) {
String name = aCookie.getName();
String value = aCookie.getValue();
writer.println(name + " = " + value);
}
}
}
Spring框架提供 @cookieValue 注释来获取HTTP cookie的值,此注解可直接用在控制器方法参数中
@GetMapping("/")
public String readCookie(@CookieValue(value = "username",
defaultValue = "Atta") String username) {
return "Hey! My username is " + username;
}



