需求是这样的
在已经写好的系统中添加管理员的操作记录。并且总管理权限可以查看这些记录。包括操作的时间 内容和操作的结果以及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的监听 保证随时可以取到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切入点对象,可以没有该参数
*/
@Before("point()")
public void before(JoinPoint joinPoint){
System.out.println("------------------------");
}
//配置后置通知,使用在方法aspect()上注册的切入点
@After("point()")
public void after(JoinPoint joinPoint) throws Throwable{
}
//配置环绕通知,使用在方法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) + "个参数为:" + 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());
}
}
网友评论