springboot使用session和cookie来免登陆
手动登陆,将cookie放入@RequestMapping(value = "/login/status",method = RequestMethod.POST)// 需要从请求中获取参数,所以需要request对象,需要将数据存放在request作用域,所以需要session对象public Object loginStatus(HttpServletRequest request, Http
·
手动登陆,将cookie放入
@RequestMapping(value = "/login/status",method = RequestMethod.POST)
// 需要从请求中获取参数,所以需要request对象,需要将数据存放在request作用域,所以需要session对象
public Object loginStatus(HttpServletRequest request, HttpSession session, HttpServletResponse response) {
/*先获取json对象*/
JSONObject jsonObject = new JSONObject();
//从请求体中拿数据
String username = request.getParameter("username");
String password = request.getParameter("password");
// 调用service的方法来获取结果
boolean res = consumerService.verifyPassword(username, password);
if (res) {
// 数据放入json
Consumer user = consumerService.selectByName(username);
jsonObject.put(Consts.CODE, 1);
jsonObject.put(Consts.MSG, "登陆成功");
jsonObject.put("userMsg",user);
// 登陆的用户放入request作用域
session.setAttribute(String.valueOf(user.getId()), user);
// 添加cookie
Cookie cookie = new Cookie("Id",String.valueOf(user.getId()));
//设置存活时间
cookie.setMaxAge(7 * 24 * 60 * 60);
// cookie放至响应头
response.addCookie(cookie);
// 将json给前端
return jsonObject;
}else{
jsonObject.put(Consts.CODE, 0);
jsonObject.put(Consts.MSG, "用户名或密码错误");
return jsonObject;
}
}
添加一个验证cookie的后端api,其实可以设置到拦截器中,但是我比较懒
@RequestMapping(value = "/login",method = RequestMethod.GET)
// 需要从请求中获取参数,所以需要request对象,需要将数据存放在request作用域,所以需要session对象,
public Object login(HttpServletRequest request, HttpSession session,
@CookieValue(value = "Id",defaultValue = "游客")String Id) {
JSONObject jsonObject = new JSONObject();
if(session.getAttribute(Id)!=null){
jsonObject.put("userMsg",session.getAttribute(Id));
jsonObject.put(Consts.CODE, 1);
jsonObject.put(Consts.MSG, "欢迎回来");
return jsonObject;
}
jsonObject.put(Consts.CODE, 0);
jsonObject.put(Consts.MSG, "太久不见,请重新登陆");
return jsonObject;
}
关于cookie在springboot的使用https://attacomsian.com/blog/cookies-spring-boot
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)