springboot项目中session和cookie
cookie例子: 添加cookie 需要在方法中添加参数 HttpServletResponse response
Cookie cookie = new Cookie("u_id", String.valueOf(u_id)); //这里设置cookie
response.addCookie(cookie);
model.addAttribute("id", u_id);
获取cookie 需要在方法中添加参数 HttpServletRequest request
Cookie[] cookies = request.getCookies();
if(cookies != null){
for(Cookie cookie : cookies){
if(cookie.getName().equals("u_id")){ //检测cookie名称是否等于u_id
return cookie.getValue();
System.out.println(cookie.getValue());
int u_id = Integer.parseInt(cookie.getValue());
model.addAttribute("userInfo",userService.getUserInfo(u_id));
}
}
}
对于session: 需要先创建一个类,因为session存储的是个对象,取出来是也要以对象格式取出来 需要在方法加入参数HttpServletRequest request
user u = new user(u_id);
request.getSession().setAttribute("u_id",new user(u_id));
可以在不同的RequsetMapping中取session 取session
user User = (user)request.getSession().getAttribute("u_id");
User.getId()
