使用@Aspectj风格的切面拦截action
第一种方式:
1.切面:
@Aspect
public class ActionBeforeAspect {
private Logger logger = Logger.getLogger(this.getClass().getName());
@Pointcut("within(com.makeprogress.struts.action.*)")//拦截所有action的execute方法
public void service(){}
@Before("service() && args(map,fo,req,..)")//
public void beforeAspect(JoinPoint jp,ActionMapping map,ActionForm fo,HttpServletRequest req){
//通过JoinPoint获得目标类名
logger.log(Level.INFO, "Action:"+jp.getTarget().getClass().getName());
//通过request对象获得用户在页面输入的用户名
String re = (String)req.getParameter("username");
logger.log(Level.INFO, "username: "+re);
}
}
2.在applicationContext.xml中只需做如下配置
<bean id="actionBeforeAspect" class="com.makeprogress.aspectj.ActionBeforeAspect"/>
第二种方式:
1.before装备
package com.makeprogress.aspectj;
import java.lang.reflect.Method;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
//实现before通知的类需要实现MethodBeforeAdvice接口
import org.springframework.aop.MethodBeforeAdvice;
public class LogBefore implements MethodBeforeAdvice {
private Logger logger = Logger.getLogger(this.getClass().getName());
public void before(Method arg0, Object[] arg1, Object arg2)
throws Throwable {
//before通知只在程序开前执行
logger.log(Level.INFO, "arg0: "+arg0.getClass().getName()+": "+arg0.getName());
logger.log(Level.INFO, "arg2: "+arg2);
logger.log(Level.INFO, arg1[0]+"开始审核数据......");
}
}
2. applicationContext.xml文件中的配置:
<!--login为action在xml中的配置, 在struts配置文件中我配置了
<controller processorClass="org.springframework.web.struts.DelegatingRequestProcessor"/>
-->
<bean name="/login" class="com.makeprogress.struts.action.LoginAction"/>
<bean id="logbefore" class="com.makeprogress.aspectj.LogBefore"/>
<bean name="loggingAutoProxy" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="beanNames">
<list>
<value>/login</value> <!--login为上面配置的action,如需要还要配置其它的action,可以在此处增加 value元素-->
</list>
</property>
<property name="interceptorNames">
<list>
<value>logbefore</value>
</list>
</property>
</bean>