spring mvc +cookie+拦截器功能 实现系统自动登陆
先看看我遇到的问题:
@ResponseBody @RequestMapping("/logout") public Json logout(HttpSession session,HttpServletRequest request,HttpServletResponse response) { Json j = new Json(); if (session != null) { // session.invalidate(); session.removeAttribute("U"); } Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if ("userCookie".equals(cookie.getName())) { cookie.setValue(""); cookie.setMaxAge(0); response.addCookie(cookie); } } } j.setSuccess(true); j.setMsg("注销成功!"); return j; }
然后看到的cookie是:
拦截器这边:
public class PermissionInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String requestUri = request.getRequestURI(); String contextPath = request.getContextPath(); String url = requestUri.substring(contextPath.length()); if (excludeUrls.contains(url)) { return true; } HttpSession session = request.getSession(); User u = (User) session.getAttribute("U"); if (null==u) { Cookie[] cookies = request.getCookies(); if (cookies!=null && cookies.length>0) { for (Cookie cookie : cookies) { if ("userCookie".equals(cookie.getName())) { String name = cookie.getValue(); if (BaseUtil.isEmpty(name)) { String[] ss = name.split(","); if (userService.exsit("name", ss[0].trim(), "pwd", ss[1].trim())) { u = userService.findEntity("name", ss[0].trim(), "pwd", ss[1].trim()); session.setAttribute("U", u); break; } } } } } } }
看到的结果是:
看出问题了吧,cookie 竟然不一样,不知道看到此处,你是否知道问题出在哪里。
我还发表了一个问题讨论:http://www.oschina.net/question/6556_233128
下面我们就进入正题了。
先看spring mvc 的拦截器:
package com.tw.interceptor; import java.util.List; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import com.tw.entity.sys.Permission; import com.tw.entity.sys.RolesPermissionRel; import com.tw.entity.sys.User; import com.tw.entity.sys.UserRoleRel; import com.tw.service.sys.PermissionService; import com.tw.service.sys.RolesPermissionRelService; import com.tw.service.sys.UserRoleRelService; import com.tw.service.sys.UserService; import com.tw.util.BaseUtil; import com.tw.util.MD5; public class PermissionInterceptor implements HandlerInterceptor { @Autowired private UserRoleRelService userRoleRelService; @Autowired private RolesPermissionRelService rolesPermissionRelService; @Autowired private PermissionService permissionService; @Autowired private UserService userService; private ListexcludeUrls; public ListgetExcludeUrls() { return excludeUrls; } public void setExcludeUrls(ListexcludeUrls) { this.excludeUrls = excludeUrls; } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String requestUri = request.getRequestURI(); String contextPath = request.getContextPath(); String url = requestUri.substring(contextPath.length()); if (excludeUrls.contains(url)) { return true; } HttpSession session = request.getSession(); User u = (User) session.getAttribute("U"); if (null==u) { Cookie[] cookies = request.getCookies(); if (cookies!=null && cookies.length>0) { for (Cookie cookie : cookies) { if ("userCookie".equals(cookie.getName())) { String name = cookie.getValue(); if (BaseUtil.isEmpty(name)) { String[] ss = name.split(","); if (userService.exsit("name", ss[0].trim(), "pwd", ss[1].trim())) { u = userService.findEntity("name", ss[0].trim(), "pwd", ss[1].trim()); session.setAttribute("U", u); break; } } } } } } if (null==u) { response.sendRedirect("login.jsp"); return false; } HandlerMethod method = (HandlerMethod)handler; Perm perm = method.getMethodAnnotation(Perm.class); if (perm==null) { return true; } Listur = userRoleRelService.findByProperty("id.userId", u.getId()); for (UserRoleRel userRoleRel : ur) { Listrp = rolesPermissionRelService.findByProperty("id.roleId", userRoleRel.getId().getRoleId()); for (RolesPermissionRel rolesPermissionRel : rp) { Permission permission = permissionService.find(rolesPermissionRel.getId().getPermissionId()); if (perm.privilegeValue().equals(permission.getPermissionCode())) { return true; } } } request.getRequestDispatcher("/error/noSecurity.jsp").forward(request, response); return false; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
再看登录实现:
@ResponseBody @RequestMapping("/login") public Json login(String name,String pwd,String remember,Model model,HttpSession session, HttpServletRequest request,HttpServletResponse response) { Json json = new Json(); if (userService.exsit("name", name.trim(), "pwd", MD5.MD5Encode(pwd.trim()))) { User u = userService.findEntity("name", name.trim(), "pwd", MD5.MD5Encode(pwd.trim())); if (u.getCancel().equals("1")) { if ("yes".equals(remember.trim())) { Cookie cookie = new Cookie("userCookie", u.getName() + "," + u.getPwd()); cookie.setMaxAge(60 * 60 * 24 * 14);//保存两周 cookie.setPath("/"); response.addCookie(cookie); } session.setAttribute("U", u); // return "redirect:/main"; json.setMsg("登陆成功"); json.setSuccess(true); return json; }else { json.setMsg("对不起你的账号还没有通过邮箱验证"); // model.addAttribute("errorMsg", "对不起你的账号还没有通过邮箱验证"); } }else { json.setMsg("用户名或密码错误"); // model.addAttribute("errorMsg", "用户名或密码错误"); } return json; // return "login"; }
还有注销的:
@ResponseBody @RequestMapping("/logout") public Json logout(HttpSession session,HttpServletRequest request,HttpServletResponse response) { Json j = new Json(); if (session != null) { // session.invalidate(); session.removeAttribute("U"); } Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if ("userCookie".equals(cookie.getName())) { Cookie cookie2 = new Cookie("userCookie", null); cookie2.setMaxAge(0); cookie2.setPath("/"); response.addCookie(cookie2); break; } } } j.setSuccess(true); j.setMsg("注销成功!"); return j; }
看到这里你是否已经知道了之前问题的存在原因呢?
我先不考诉你们,谁知道这里面的错误原因可以在上面留言哦!
我想页面就简单多了,因为是执行方法之前拦截判断的,所以只要你存放有cookie无论调用那个页面都可以自动实现登陆。
补充一个问题:HTTP Status 500 - Request processing failed; nested exception is java.lang.IllegalArgumentException: Control character in cookie value or attribute.
看到这样的错误你知道是怎么回事么?