您的位置:首页 > 编程语言 > Java开发

springboot项目中session和cookie

2019-07-28 13:36 288 查看

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()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: