用AOP自动管理Session数据

来源:互联网 发布:c语言点滴 epub 编辑:程序博客网 时间:2024/05/01 13:07

在互联网应用开发中,由于涉及到分布式运算,一般来说都是不使用容器默认的Session管理的,如Tomcat。因为这些容器的Session管理,默认是基于单机的(Tomcat可以配置为用Memcache管理Session,这里不谈)。这种情况下,我们一般用Redis之类的高速缓存来保存Session,然后把SessionId通过Cookie下发到浏览器。

那么在编程的时候,大量方法需要读取SessionId,然后从Redis读取Session内容,这样就有大量的模板代码要写,即使你封装起来成为一个方法,也至少要调用一次。

我们可以用Spring的AOP来解决,首先定义一个Around的AOP,拿到他的ProceedingJoinPoint参数,从这个参数获取切面方法中是否有SessionUser对象,如果有,则读取后放入,这样在Controler里面就可以直接拿到Session对象。

@Around("execution(* cn.*.controler..*.*(..)) && args(sessionId)",argNames="sessionId")    public void onHttp(ProceedingJoinPoint joinPoint,String sessionId){        Object[] args=joinPoint.getArgs();        for(int i=0;i<args.length;i++){            if(args[i] instanceof SessionUser){                args[i] = getSessionUserBySessionId(sessionId);            }        }        try {            joinPoint.proceed(args);        } catch (Throwable throwable) {            throwable.printStackTrace();        }}

Controler方法类似如下

@RequestMapping("/usr/edit")public String userEdit(@CookieValue String sessionId,SessionUser sessionUser){    }


0 0
原创粉丝点击