Chinaunix首页 | 论坛 | 博客
  • 博客访问: 783925
  • 博文数量: 738
  • 博客积分: 7000
  • 博客等级: 少将
  • 技术积分: 5000
  • 用 户 组: 普通用户
  • 注册时间: 2008-09-12 09:00
文章分类

全部博文(738)

文章存档

2011年(1)

2008年(737)

我的朋友

分类:

2008-09-12 09:02:15

   在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文件:



Spring Quick Start








.*excute.*








com.wysm.netstar.test.springaop.CheckInterface





myPointcutAdvisor2





  这个定义文件指明了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");
}
}

【责编:yuan】

--------------------next---------------------

阅读(316) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~