今天看代码时,发现Spring中的这个类也可以实现拦截器的功能,就研究了下,该类在org.springframework.web.servlet.handler.HandlerInterceptorAdapter这个包下面。

下面看下代码:

public class MemberInterceptor extends HandlerInterceptorAdapter {

//预处理
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return true;

}
//后处理
public void postHandle(
HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
throws Exception {
}
//返回处理
public void afterCompletion(
HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
}
/**
* 处理异步请求
*/
public void afterConcurrentHandlingStarted(
HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
}
}

该类是一个抽象类,它实现了AsyncHandlerInterceptor接口

public abstract class HandlerInterceptorAdapter implements AsyncHandlerInterceptor


进一步查看源码发现该接口继承了HandlerInterceptor接口

public interface AsyncHandlerInterceptor extends HandlerInterceptor {

/**
* Called instead of {@code postHandle} and {@code afterCompletion}, when
* the a handler is being executed concurrently. Implementations may use the
* provided request and response but should avoid modifying them in ways
* that would conflict with the concurrent execution of the handler. A
* typical use of this method would be to clean thread local variables.
*
* @param request the current request
* @param response the current response
* @param handler handler (or {@link HandlerMethod}) that started async
* execution, for type and/or instance examination
* @throws Exception in case of errors
*/
void afterConcurrentHandlingStarted(
HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception;

}


public interface HandlerInterceptor {
boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception;
void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)throws Exception;
void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)throws Exception;
}public interface HandlerInterceptor {
boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception;
void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)throws Exception;
void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)throws Exception;
}