@RestController public class LoginController { @Resource(name = "userServiceImpl") private IUserService userService; @RequestMapping(value = "/login/login", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) public Result<User> login(HttpRequest request, HttpServletResponse response) { return userService.login(request, response); } @RequestMapping(value = "/login/check", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) public Result<User> check(HttpServletRequest request, HttpServletResponse response) { Result<User> result = new Result<>(); String userId = SessionContext.get("user_id"); if (StringUtils.isEmpty(userId)) { Cookie loginTypeCookie = new Cookie("login_type", "0"); loginTypeCookie.setPath("/"); loginTypeCookie.setSecure(true); response.addCookie(loginTypeCookie); result.set("login_type", 0); } else { Cookie loginTypeCookie = new Cookie("login_type", "1"); loginTypeCookie.setPath("/"); loginTypeCookie.setSecure(true); response.addCookie(loginTypeCookie); result.set("login_type", 1); result.set("user_id", SessionContext.get("user_id")); result.set("user_name", SessionContext.get("user_name")); result.set("login_name", SessionContext.get("login_name")); result.set("user_image_id", SessionContext.get("user_image_id")); result.set("role_type", SessionContext.get("role_type")); // 检查token 是否需要更新 HttpSession session = request.getSession(false); if(session != null){ // 更新 session String issueAtStr = SessionContext.get("issueAt"); if(StringUtils.isNotEmpty(issueAtStr)){ Date issueAt = DateUtils.stringToDate(issueAtStr, DateConst.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS_SSS); if(issueAt != null && TokenUtils.shouldTokenRefresh(issueAt)){ Map<String, Object> claims = new HashMap<>(10); claims.put("user_id", String.valueOf(SessionContext.getInt("user_id"))); claims.put("user_name", SessionContext.get("user_name")); claims.put("login_name", SessionContext.get("login_name")); claims.put("user_image_id", SessionContext.get("user_image_id")); claims.put("role_type", String.valueOf(SessionContext.getInt("role_type"))); String token = TokenUtils.createToken(claims); session.setAttribute("token", token); result.set("token", token); Cookie tokenCookie = new Cookie("token", token); tokenCookie.setPath("/"); response.addCookie(tokenCookie); } } } } return result; } @RequestMapping(value = "/login/exit", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) public Result<User> exit(HttpRequest request) { HttpSession session = request.getSession(false); if (session != null) { session.invalidate(); } return new Result<>(); } }
时间: 2023-06-09 12:08:01 浏览: 170
Laravel 自动生成验证的实例讲解:login / logout
请问您的问题是这段代码的作用是什么吗?
回答:这段代码是一个基于 Spring MVC 框架的登录控制器,其中包含两个请求映射方法,一个是用于用户登录验证的方法,另一个是用于检查登录状态的方法。在用户登录成功后,该控制器会在客户端写入一个名为 "login_type" 的 cookie 用于标识登录类型,并设置返回结果集合中的相应字段。同时,该控制器还会检查用户的登录状态并使用 Session 上下文进行相关操作。
阅读全文