移:使用Spring AOP实现MVC拦截器

来源:互联网 发布:中国人口迁移数据 编辑:程序博客网 时间:2024/06/05 05:19
使用Spring AOP实现MVC拦截器
Webwork实现了拦截器,但未用AOP技术,只不过是预留了接口。下面定义一个使用Spring AOP作为拦截器的伪代码
定义Action,就是AOP中的Target:
public interface Action {
    public void setDomain(DomainObject object);//设置领域对象,每个Action都有一个领域对象
    public void execute();
}
定义领域对象:
import java.io.Serializable;
public interface DomainObject extends Serializable{
}
定义拦截器:
public interface Interceptor{
    public void intercept();
}
定义Advicer:
import java.lang.reflect.Method;
import java.util.List;
import org.springframework.aop.BeforeAdvice;
public class ActionAdvicer implements BeforeAdvice {
    private List interceptors;
    public void setInterceptors(List list){
        this.interceptors = list;
    }
  
    public void before(Method method, Object[] args, Object target) throws Throwable {
        //执行所有的拦截器方法
        for(int i=0; i<interceptors.size(); i++){
            ((Interceptor)interceptors.get(i)).intercept();
        }
    }
}
定义BeanManager获得对象,应该使用Spring自带的
public class BeanManager {
    public static Object getBean(String beanName){
        return null;
    }
}
测试类
public class TestMVC {
    public static void main(String[] args){
        //定义http请求字符串
        String httpRequestString = "";
        //获得Action
        Action action = (Action)BeanManager.getBean(httpRequestString);
        //获得Iterceptors
        List interceptors = new ArrayList();
        Interceptor interceptor = (Interceptor)BeanManager.getBean(httpRequestString);
        interceptors.add(interceptor);
        //...
      
        //定义AOP
        ActionAdvicer advicer = new ActionAdvicer();
        ProxyFactory proxyFactory = new ProxyFactory();
        proxyFactory.addAdvice(advicer);
        proxyFactory.setTarget(action);
      
        //设置打断器
        advicer.setInterceptors(interceptors);
      
        //执行
        Action actionBean = (Action) proxyFactory.getProxy();
        actionBean.execute();
    }
}
流程如下:
程序入口是HttpRequest,获得request所有参数,根据参数从配置文件获得相应配置:
Action,此次调用参与的interceptors。
设置好Advicer,把参数中的值保存至某个类中(Webwork的OgnlValueStack)。OgnlValueStack应该是 ThreadLocal的?待定。反正,此次调用所涉及到的Interceptors都可以访问到OganValueStack中的值。
调用action.execute()方法
调用前,获得aop的before advicer,此方法会执行所有Interceptor的interceptor方法。
其中,某个Interceptor会把ValueStack中的内容赋值到action的domainObject中。
这样,使用AOP自动把http请求赋到相应的action的领域对象过程完成!
原创粉丝点击