SpringBoot使用Cookie
SpringBoot使用Cookie
·
设置Cookie
@GetMapping("/setCookie")
public String setCookie(HttpServletResponse response) {
// 创建一个 cookie对象
Cookie cookie = new Cookie("username", "lixianhe");
//将cookie对象加入response响应
response.addCookie(cookie);
return "Cookie设置成功";
}
获取Cookie
方式一
@GetMapping(value = "/getCookies")
public String readCookies(HttpServletRequest request, HttpServletResponse response) throws IOException {
//设置contentType,解决中文乱码
response.setContentType("text/html;charset=utf-8");
Map<String, Object> map = new HashMap<>();
// 获取Cookie
Cookie[] cookies = request.getCookies();
// 遍历Cookie
for (Cookie aCookie : cookies) {
String name = aCookie.getName();
String value = aCookie.getValue();
map.put(name, value);
}
return JSON.toJSONString(map);
}
方式二
Spring框架提供@CookieValue注释来获取Cookie的值
@GetMapping("/")
public String readCookie(@CookieValue(value = "username", required = false) String username) {
return username;
}
更多推荐
所有评论(0)