使用Spring AOP和Cookie做网站免登陆

来源:互联网 发布:蘑菇插件mac 编辑:程序博客网 时间:2024/04/29 22:00

在我们平时浏览网站的时候,会发现很多网站,在你登陆一次后,下次登陆就不需要重新登陆了。其原理就是登陆的时候将,Cookie中取出并登陆。下面是js代码

function SetCookie(name, value) {        var today = new Date();        var expires = new Date();        expires.setTime(today.getTime() + 1000*60*60*24*7);        document.cookie = name + "=" + escape(value) + "; expires=" + expires.toGMTString() + ";path=/";    }

页面登陆时使用js将用户名和密码用Cookie存储起来,;path=/是说明域名下的所有路径都能取得Cookie,不加说明只有此页面的路径可以取得。

后端代码

@Aspect  @Component  public class AOP_loginfo {    @Autowired    IUserService userService;    /**       * 所有带RequestMapping注解的方法       */      private final static String el = "@annotation(org.springframework.web.bind.annotation.RequestMapping)";      @Before(el)      public void before() {        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();        HttpSession session = request.getSession();        User user = (User) session.getAttribute(CORER.SESSION_USER);        Cookie[] cookies = request.getCookies();        if (cookies != null && user == null) {            String email = null;            String password = null;            for (Cookie cookie : cookies) {                String name = cookie.getName();                if ("email".equals(name)) {                    email = cookie.getValue();                }                if ("password".equals(name)) {                    password = cookie.getValue();                }            }            user = new User();            user.setEmail(email);            user.setPassword(password);            //登陆            Message<User> loginMsg = userService.login(user);            if (loginMsg.isStatus()) {                user = loginMsg.getData();                request.getSession().setAttribute(CORER.SESSION_USER, user);            }        }    }      @After(el)      public void after() {        System.out.println("执行之后");      }      @Around(el)      public Object around(ProceedingJoinPoint p) {          for (Object obj : p.getArgs()) {              System.out.println("参数:" + obj);          }          Object ob = null;          try {              System.out.println("around前");              ob = p.proceed();              System.out.println("around后");          } catch (Throwable e) {              e.printStackTrace();          }          return ob;      }      @AfterThrowing(value = el, throwing="e")      public void throwing(Exception e){          System.out.println("出异常了"+e);      }  }

如果取到用户名和密码并登陆成功,就将信息放入Session中。


后端其实使用过滤器,或者spring的拦截器都是可以实现的。大家可以看怎么方便怎么实现。这是我在一个论坛的开源项目中做的功能,因为项目中,没有spring的xml的配置文件。使用的Spring4和servlet3,零配置文件。最初我用的servlet的过滤器,但WebApplicationContextUtils获取的WebApplicationContext为null,无法得到service来登陆。找了一下原因,是因为项目中没有web.xml即没有添加ContextLoaderListener, WebApplicationContextUtils没有初始化,我试了下在java类中添加此监听器,都没有成功。在一个朋友的帮助下换成了现在这种方法。发现自己对Spring的了解不够,以后准备多阅读些Spring的源码。

0 0
原创粉丝点击