在上一篇文章里提到了可以让 dwr自动往service里面注入一个与servlet相关的对象,作为参数。只是这样,要每个service都加上这样的一个参数,奇丑无比!想了 想,决定就让dwr污染一下,service保留原样。只是增加一个methodbeforeadvice(正是它让dwr的api污染了一下。),来对 service的方法进行拦截,可以在service的调用之前对操作进行所谓的身份验证,授权之类的操作。完整的拦截模块几个类文件加个spring配 置文件搞定。
实现拦截功能的类有:
一、maininteceptor,主拦截器,所以dwr的远程调用都会被拦截,当然, 调用是细到方法级的,可配置的,该类实现了spring aop的methodbeforeadvice接口,该类有一个集合成员变量,成员为iinteceptor。
二、iinteceptor,是一个接口,仅有一个execute(aopcontext context)函数。该接口是拦截器(与前面的主拦截器不同,本接口定义的拦截器是可以由用户去实现,并且可以有多个)。实现接口只需要实现方法。这些 拦截器会被主拦截器回调。 比如要实现一个身份验证的拦截,secuityinteceptor,在配置文件中把这个拦截器设置为主拦截器的属性即可获得回调。
三、aopcontext,aop上下文。在主拦截器调用iinteceptor的对象时,把这个上下文对象作为参数来调用子拦截器。从该上下文可获得一系列信息,如httpsession,httprequest等。甚至你可以自已设置属性。
下面看一些代码片断:
maininteceptor:
private list<iinterceptor> interceptors;//定义一系列的子拦截器
public void setinterceptors(list<iinterceptor> interceptors) {
this.interceptors = interceptors;
}
在before(method method, object[] params, object target)方法里:
webcontext ctx = webcontextfactory.get();//唯一被dwr污染的地方
httpsession session = ctx.getsession();
aopcontext context = new aopcontext(); context.setsession(session);
for(iterator it = interceptors.iterator(); it.hasnext();){
iinterceptor interceptor = (iinterceptor) it.next();
interceptor.execute(context);
}
iinterceptor:
public interface iinterceptor {
public void execute(aopcontext context);
}
aopcontext就不必贴出来了, 随自已定义些什么属性,不过就内置了一个map,用来保存数据罢了。
下面来看看配置文件:
<beans>
<!--将要暴露给dwr的service-->
<bean id="bookmanager" class="org.springframework.aop.framework.proxyfactorybean">
<property name="proxyinterfaces">
<value>net.jf.ajax.business.bookmanager</value>
</property>
<property name="target">
<ref local="bookmanagerimpl"/>
</property>
<property name="interceptornames">
<list>
<value>dwradvisor</value>
</list>
</property>
</bean>
<bean id="bookmanagerimpl" class="net.jf.ajax.business.impl.bookmanagerimpl"/>
<!--装配器?如果看不懂,先看看spring的aop吧 :p-->
<bean id="dwradvisor" class="org.springframework.aop.support.regexpmethodpointcutadvisor">
<property name="advice">
<ref local="dwrinterceptor"/>
</property>
<property name="patterns">
<list>
<value>.*.*</value>
</list>
</property>
</bean>
<!--主拦截器,给它设置子拦截器-->
<bean id="dwrinterceptor" class="net.jf.ajax.iterceptor.maininterceptor">
<property name="interceptors">
<list>
<ref bean="test"/>
</list>
</property>
</bean>
<!--其中一个子拦截器的实现-->
<bean id="test" class="net.jf.ajax.iterceptor.testinterceptor"/>
</beans>
就 这样,在配置dwr的配置文件时,配置<creator>时使用spring的creator就可以直接使用上面的service了。当 dwr远程请求时,在配置范围内的方法的调用都会被主拦截器拦截,并且遍历、执行所有子拦截器。原有的service不需要改动,只需要多加一个 spring的配置文件,将原有的service再加一层aop的轻纱。
这是一种实现方法。如果有别的方法让dwr更安全、有效,请一定告知。:)
闽公网安备 35060202000074号