SpringMVC(七):利用Cookie实现登陆验证
一、登陆时要往将用户登陆的信息存入Cookie
@RequestMapping("/doLogin") @ResponseBody public String doLogin(String userName, String userPassword, HttpServletResponse response) { User user = userService.queryUserByName(userName); if (user != null && user.getUserPassword().equals(userPassword)) { Cookie cookie = new Cookie(Constant.USERNAME, userName); cookie.setMaxAge(7*24*60*60); response.addCookie(cookie); return "true"; } return "false"; }
cookie.setMaxAge()是设置cookie的过期时间,这里设置的是7天过期,如果不进行时间设置,cookie默认会在浏览器关闭时过期。
二、拦截器中验证cookie
public class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals(Constant.USERNAME)) return true; } } response.sendRedirect("/login"); return false; } }
三、进入登陆页面时判断cookie,若存在则无需登录,不存在则需要登录
@RequestMapping("/login") public String loginPage(HttpServletRequest request, String userName, Model model) { Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (Constant.USERNAME.equals(cookie.getName())) return "redirect:/user/main"; } } if (userName != null) model.addAttribute("userName", userName); return "login"; }
四、注销时删除cookie
@RequestMapping("/doLogout") public String doLogout(HttpServletRequest request, HttpServletResponse response) { Cookie[] cookies = request.getCookies(); if (cookies != null){ for (Cookie cookie : cookies) { if (cookie.getName().equals(Constant.USERNAME)) { cookie.setMaxAge(0); cookie.setPath("/"); response.addCookie(cookie); } } } return "redirect:/"; }
(本文仅作个人学习记录用,如有纰漏敬请指正)