首页 > 编程知识 正文

springboot项目中session和cookie

时间:2023-05-03 20:41:19 阅读:285651 作者:3013

cookie例子:
添加cookie
需要在方法中添加参数 HttpServletResponse response

Cookie cookie = new Cookie("u_id", String.valueOf(u_id)); //这里设置cookieresponse.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()

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。