package com.myparamita.interceptors; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ControllerInterceptor implements HandlerInterceptor { long inTime; public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { inTime = System.currentTimeMillis(); System.out.println("in controller: "+request.getServletPath()); return true; } public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { long timeGap = Math.abs(System.currentTimeMillis() - inTime); System.out.println("out controller: "+"{\"controllerPath\":\"" + request.getServletPath() + "\",\"timeGap\":" + timeGap + "}"); } public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
纯注解方式
采用此方式,配置均通过注解方式在拦截类中进行设置,如下:
package com.myparamita.aop; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; @Aspect @Component public class LogInterceptor { @Pointcut("execution(public * com.myparamita.controller.*.*(..))") public void myMethod() { } @Before("myMethod()") public void before() { System.out.println("=========================================method start"); } @After("myMethod()") public void after() { System.out.println("=========================================method after"); } }
spring配置文件中添加:
基于Spring定义的MethodInterceptor
在Spring中共提供了四种Advice用来支持对方法调用时施加的不同行为
BeforeAdvice:具体接口:MethodBeforeAdvice 在目标方法调用之前调用的AdviceAfterAdvice:具体接口:AfterReturningAdvice 在目标方法调用并返回之后调用的AdviceAroundAdvice:具休接口:MethodInterceptor 在目标方法的整个执行前后有效,并且有能力控制目标方法的执行ThrowsAdvice:具体接口:ThrowsAdvice 在目标方法抛出异常时调用的Advice
在以上四种Advice中最为特别的就是MethodInterceptor:方法拦截器.它的特别之处在于:
首先他所在的包并不Srping中的包而是:org.aopalliance.intercept包.即MethodInterceptor实现了AOP联盟接口,这一点保证了它较之其他的Advice更具有通用性,因为它可以在任何基于AOP联盟接口实现的AOP系统中使用.
第二点也就是其最为突出的一点就是它所具有的其他Advice所不能匹敌的功能:在目标方法的整个执行前后有效,并且有能力控制目标方法的执行!
package com.myparamita.aop; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; public class TestInterceptor implements MethodInterceptor { @Override public Object invoke(MethodInvocation invocation) throws Throwable { System.out.println("======================before===="); //此处可根据实际情况决定是否执行目标方法 Object ret = invocation.proceed(); System.out.println("======================after===="); return ret; } }