需求是這樣的
在已經(jīng)寫好的系統(tǒng)中添加管理員的操作記錄。并且總管理權(quán)限可以查看這些記錄树瞭。包括操作的時間 內(nèi)容和操作的結(jié)果以及IP地址能耻。
查找各方面資料后号涯。感覺最適合我們項目的就是Spring Aop 做切面操作。
操作過程很簡單青扔。
首先在 Spring的配置文件中 applicationContext.xml 添加對aop的掃描并打開自動代理
<!-- 配置aop -->
<context:component-scan base-package="com.onepay.aop"></context:component-scan>
<!-- 激活自動代理 -->
<aop:aspectj-autoproxy proxy-target-class="true" ></aop:aspectj-autoproxy>
在web.xml中添加對對webcontext的監(jiān)聽 保證隨時可以取到request和response
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
之后就可以寫切面 攔截service的請求
/**
* 登錄操作切面
* @author dell
*
*/
@Component
@Aspect
public class LoginAspect {
@Resource
private HttpServletRequest request;
//配置切點
@Pointcut("execution(* com.onepay.service.WYUserService.*(..))")
public void point(){ }
/*
* 配置前置通知,使用在方法aspect()上注冊的切入點
* 同時接受JoinPoint切入點對象,可以沒有該參數(shù)
*/
@Before("point()")
public void before(JoinPoint joinPoint){
System.out.println("------------------------");
}
//配置后置通知,使用在方法aspect()上注冊的切入點
@After("point()")
public void after(JoinPoint joinPoint) throws Throwable{
}
//配置環(huán)繞通知,使用在方法aspect()上注冊的切入點
@Around("point()")
public Object around(ProceedingJoinPoint joinPoint)throws Throwable{
Object returnVal = joinPoint.proceed();
System.out.println("around 目標方法名為:" + joinPoint.getSignature().getName());
System.out.println("around 目標方法所屬類的簡單類名:" + joinPoint.getSignature().getDeclaringType().getSimpleName());
System.out.println("around 目標方法所屬類的類名:" + joinPoint.getSignature().getDeclaringTypeName());
System.out.println("around 目標方法聲明類型:" + Modifier.toString(joinPoint.getSignature().getModifiers()));
Object[] args = joinPoint.getArgs();
for (int i = 0; i < args.length; i++) {
System.out.println("around 第" + (i + 1) + "個參數(shù)為:" + args[i]);
}
System.out.println("around 返回值:"+returnVal);
//這里必須返回returnVal 否則controller層將得不到反饋源织。并且這個returnVal可以在這里修改會再返回到controller層。
return returnVal;
}
//配置后置返回通知,使用在方法aspect()上注冊的切入點
@AfterReturning("point()")
public void afterReturn(JoinPoint joinPoint)throws Throwable{
System.out.println("------------------------");
}
//配置拋出異常后通知,使用在方法aspect()上注冊的切入點
@AfterThrowing(pointcut="point()", throwing="ex")
public void afterThrow(JoinPoint joinPoint, Exception ex){
System.out.println("afterThrow " + joinPoint + "\t" + ex.getMessage());
}
}