在web开发中,用户对网页的访问权限检查是一个重要的环节。以strust为例,我们需要在action的excute方法中编写相关的代码(一般是调用基类的函数),也很显然,在每个action中这是一种重复劳动。 如果我们在excute运行之前,能够自动去调用基类的权限检查函数,这无疑是个好的解决办法。aop就为我们提供了这样一种解决方法。
下面以一个简化的实例介绍实现的办法。
首先我们做一个接口:public interface checkinterface { public abstract void check(string name); public abstract void excute(string name); }
再做一个基类:
public abstract class baseclass implements checkinterface { public baseclass() { } public void check(string name){ if (name.equals("supervisor")) system.out.println("check pass!!"); else { system.out.println("no access privilege! please do sth. else!"); } } }
再做一个测试类:
public class excuteclass extends baseclass { public excuteclass() { }
public void excute(string name){ system.out.println("excute here!"+name); } } 好了,下面做一个通知类(advice):
import org.springframework.aop.methodbeforeadvice; import java.lang.reflect.method; import org.apache.log4j.logger;
public class beforeadvisor implements methodbeforeadvice { private static logger logger=logger.getlogger(beforeadvisor.class); public void before(method m, object[] args, object target) throws throwable { if (target instanceof checkinterface){ logger.debug("is instanceof checkinterface!!!"); checkinterface ci=(checkinterface)target; ci.check((string)args[0]); } } }
其中重要的before方法的参数:object target传入的通知的对象(即测试类的接口),method m, object[] args分别是该对象被调用的方法和参数。我们再来作spring bean定义xml文件: <?xml version="1.0" encoding="utf-8"?> <!doctype beans public "-//spring//dtd bean//en" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <description>spring quick start</description> <bean id="myadvisor" class="com.wysm.netstar.test.springaop.beforeadvisor"/>
<bean id="mypointcutadvisor2" class="org.springframework.aop.support.regexpmethodpointcutadvisor"> <property name="advice"> <ref local="myadvisor" /> </property> <property name="patterns"> <list> <value>.*excute.*</value> </list> </property> </bean>
<bean id="checkinterface" class="com.wysm.netstar.test.springaop.excuteclass"/>
<bean id="mycheckclass" class="org.springframework.aop.framework.proxyfactorybean"> <property name="proxyinterfaces"> <value>com.wysm.netstar.test.springaop.checkinterface</value> </property> <property name="target"> <ref local="checkinterface" /> </property> <property name="interceptornames"> <value>mypointcutadvisor2</value> </property> </bean>
</beans>
这个定义文件指明了excuteclass为监视对象,它的excute方法被执行的时候,beforeadvisor将被调用。 最后是测试类:
import junit.framework.testcase; import org.springframework.context.applicationcontext; import org.springframework.context.support.filesystemxmlapplicationcontext; public class springtestcase2 extends testcase { checkinterface test=null; protected void setup() throws exception { super.setup(); applicationcontext ctx=new filesystemxmlapplicationcontext("src/com/wysm/netstar/test/springaop/aoptest.xml"); test = (checkinterface) ctx.getbean("mycheckclass"); } protected void teardown() throws exception { super.teardown(); } public void testexcute(){ test.excute("supervisor"); } }
|