在中,用戶對網頁的訪問權限檢查是一個重要的環節。以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");
}
}
新聞熱點
疑難解答