手动登陆,将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