SpringAOP在DWR安全上的应用

王朝other·作者佚名  2008-05-31
宽屏版  字体: |||超大  

在上一篇文章里提到了可以让 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>

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有