先看看我遇到的问题:

@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();
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>) {
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[].trim(), "pwd", ss[].trim())) {
u = userService.findEntity("name", ss[].trim(), "pwd", ss[].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>) {
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[].trim(), "pwd", ss[].trim())) {
u = userService.findEntity("name", ss[].trim(), "pwd", ss[].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("")) {
if ("yes".equals(remember.trim())) {
Cookie cookie = new Cookie("userCookie", u.getName() + "," + u.getPwd());
cookie.setMaxAge( * * * );//保存两周
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();
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.

看到这样的错误你知道是怎么回事么?

spring mvc +cookie+拦截器功能 实现系统自动登陆的更多相关文章

  1. Spring mvc登录拦截器

    自己实现的第一个Spring mvc登录拦截器 题目要求:拒绝未登录用户进入系统,只要发现用户未登录,则将用户请求转发到/login.do要求用户登录 实现步骤: 1.在spring的配置文件中添加登 ...

  2. 玩转spring MVC(七)----拦截器

    继续在前边的基础上来学习spring MVC中拦截器的使用,下面通过一个例子来实现(完整项目在这里下载:http://download.csdn.net/detail/u012116457/84334 ...

  3. Spring MVC 使用拦截器优雅地实现权限验证功能

    在上一篇 SpringAOP 实现功能权限校验功能 中虽然用AOP通过抛异常,请求转发等勉强地实现了权限验证功能,但感觉不是那么完美,应该用拦截器来实现才是最佳的,因为拦截器就是用来拦截请求的,在请求 ...

  4. [转载] Spring MVC - 处理器拦截器

    5.1.处理器拦截器简介 Spring Web MVC的处理器拦截器(如无特殊说明,下文所说的拦截器即处理器拦截器)类似于Servlet开发中的过滤器Filter,用于对处理器进行预处理和后处理.   ...

  5. Spring MVC定义拦截器

    拦截器: package sy.Interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http ...

  6. [Spring MVC] - Interceptor 拦截器

    Spring MVC中的Interceptor与Struts2的差不多. 下面是一个简单的Interceptor登陆验证例子: 1.需要在spring的配置文件中加入这段: <!-- 自定义拦截 ...

  7. spring mvc 配置文件拦截器过滤url

    最近在用spring mvc拦截器,sprin 版本号4.0.6.RELEASE, <mvc:interceptor> <mvc:mapping path="/admin/ ...

  8. Spring Mvc session拦截器实现

    Spring Mvc拦截器实现session过期跳转到登录页面 配置拦截器 <mvc:interceptors> <mvc:interceptor> <mvc:mappi ...

  9. 基于Spring MVC 实现拦截器

    Spring MVC 拦截器 一,具体内容: 在所有的开发之中拦截器属于一个重要的组件,可以说几乎所有的项目都会提供的概念应用,不管是Spring MVC,还是Struts 2.x都是提供有拦截器的, ...

随机推荐

  1. pod update --verbose --no-repo-update

    最近使用CocoaPods来添加第三方类库,无论是执行pod install还是pod update都卡在了Analyzing dependencies不动 原因在于当执行以上两个命令的时候会升级Co ...

  2. Asteroids(最小点覆盖)

    Asteroids Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 18183   Accepted: 9905 Descri ...

  3. switch case ,while, do while,enum

    using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace C_编辑 ...

  4. SWIFT学习笔记01

    1.Swift.用来推断option是不是nil,相当于OC的 if(option) if let name = option{ greeting = "if=====" }els ...

  5. 【web开发学习笔记】Structs2 Result学习笔记(三)带參数的结果集

    Result学习笔记(三)带參数的结果集 第一部分:代码 //前端 <head> <meta http-equiv="Content-Type" content= ...

  6. 【论文阅读】Retrieving Similar Similar Styles to Parse Clothing(相关工作)

    发表于2015年5月PAMI 作者: Kota Yamaguchi, M.Hadi Kiapour, Luis E. Ortiz, Tamara L. Berg 相关工作: [服装检索Clothing ...

  7. 循环调用修正sic86 2改后的(除了第一年有点诡异,其他年份可以正常修复)

    create or replace procedure rebuild_sic86_wyl(pi_aac001 in number, po_fhz out varchar2, po_msg out v ...

  8. 一天一个类--NIO 之Buffer

    java.nio  --- 定义了 Buffer 及其数据类型相关的子类.其中被 java.nio.channels 中的类用来进行 IO 操作的 ByteBuffer 的作用非常重要. java.n ...

  9. java --- 对象的创建过程

    java 对象创建的过程 存在了继承关系之后,对象创建过程如下: 1.分配空间.要注意的是,分配空间不光是分配子类的空间,子类对象中包含的父类对象所需要的空间,一样在这一步统一分配.在分配的空间的时候 ...

  10. Arachnid包含一个简单的HTML剖析器能够分析包含HTML内容的输入流

    Arachnid是一个基于Java的web spider框架.它包含一个简单的HTML剖析器能够分析包含HTML内容的输入流.通过实现Arachnid的子类就能够开发一个简单的Web spiders并 ...