HandlerInterceptor与MethodInterceptor
HandlerInterceptor是springMVC项目中的拦截器,它拦截的目标是请求的地址,比MethodInterceptor先执行。实现一个HandlerInterceptor拦截器可以直接实现HandlerInterceptor接口,也可以继承HandlerInterceptorAdapter类。这两种方法殊途同归,其实HandlerInterceptorAdapter也就是声明了HandlerInterceptor接口中所有方法的默认实现,而我们在继承他之后只需要重写必要的方法。下面就是HandlerInterceptorAdapter的代码,可以看到一个方法只是默认返回true,另外两个是空方法
- public abstract class HandlerInterceptorAdapter implements HandlerInterceptor {
- /**
- * This implementation always returns <code>true</code>.
- */
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
- throws Exception {
- return true;
- }
- /**
- * This implementation is empty.
- */
- public void postHandle(
- HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
- throws Exception {
- }
- /**
- * This implementation is empty.
- */
- public void afterCompletion(
- HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
- throws Exception {
- }
- }
- MethodInterceptor是AOP项目中的拦截器,它拦截的目标是方法,即使不是controller中的方法。实现MethodInterceptor拦截器大致也分为两种,一种是实现MethodInterceptor接口,另一种利用AspectJ的注解或配置
-
下面是基于注解的AspectJ方式
- public class MethodInvokeInterceptor implements MethodInterceptor {
- @Override
- public Object invoke(MethodInvocation methodInvocation) throws Throwable {
- System.out.println("before method invoke");
- Object object = methodInvocation.proceed();
- System.out.println("after method invoke");
- return object;
- }
- }
- @Component
- @Aspect
- public class AutoAspectJInterceptor {
- @Around("execution (* com.test.controller..*.*(..))")
- public Object around(ProceedingJoinPoint point) throws Throwable{
- System.out.println("AutoAspectJInterceptor begin around");
- Object object = point.proceed();
- System.out.println("AutoAspectJInterceptor end around");
- return object;
- }
- }
当然,这一切都离不开配置,具体看配置中的注释- @Component
- public class AspectJInterceptor {
- public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
- System.out.println("AspectJInterceptor around before");
- Object object = proceedingJoinPoint.proceed();
- System.out.println("AspectJInterceptor around after");
- return object;
- }
- }
- <!-- 自定义拦截器 ,先过mvc:interceptors-->
- <bean id="methodInvokeInterceptor" class="com.test.interceptor.MethodInvokeInterceptor"/>
- <bean id="aspectInterceptor" class="com.test.interceptor.AspectJInterceptor"/>
- <aop:config>
- <!--切入点,controlller -->
- <aop:pointcut id="pointcut_test" expression="execution(* com.test.controller..*.*(..))" />
- <!--在该切入点使用自定义拦截器 ,按照先后顺序执行 -->
- <aop:advisor pointcut-ref="pointcut_test" advice-ref="methodInvokeInterceptor" />
- <aop:aspect ref="aspectInterceptor">
- <aop:around method="around" pointcut="execution(* com.test.controller..*.*(..))"/>
- </aop:aspect>
- </aop:config>
- <!-- 自动扫描使用了aspectj注解的类 -->
- <aop:aspectj-autoproxy/>