Interceptor Interceptor for interception Controller Layer interface , It's kind of like Spring Of AOP, however AOP For a single approach .Interceptor It's about Controller Interface and can handle request and response object .

1 HandlerInterceptor Definition of interface

Let's see first HandlerInterceptor Definition of interface , Three interfaces are defined , namely preHandle,postHandle,afterCompletion.
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; }

preHandle Is the call Controller Previously called , When back false after , Will skip subsequent interceptors , And will not execute all interceptors postHandle, And call return true Of the interceptor afterCompletion method .
postHandle Is the call Controller Later called , But in rendering View Before page .

afterCompletion It's the end of the call Controller Interface , Rendering View Last page call . return true All interceptors of will call the interceptor afterCompletion method , In reverse order .


and HandlerInterceptor It's very similar to having one AsyncHandlerInterceptor Interface , It's just one more afterConcurrentHandlingStarted Methods , Called when an interface uses an asynchronous method .
public interface AsyncHandlerInterceptor extends HandlerInterceptor { void
afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse
response, Object handler)throws Exception; }
2 HandlerInterceptor Definition of interface

2.1 DispatcherServlet in doDispatch Main processing logic

DispatcherServlet in doDispatch() namely springMVC Main processing logic of . Therefore, it must contain the main processing logic of the interceptor
protected void doDispatch(HttpServletRequest request, HttpServletResponse
response)throws Exception { try { try { //....... Omit code // return HandlerExecutionChain
It contains the interceptor queue mappedHandler = getHandler(processedRequest);
// Call interceptor PreHandle method , If back false Do not execute Controller logic , Do not call PostHandle method if
(!mappedHandler.applyPreHandle(processedRequest, response)) {return; } //
handle Controller layer mv = ha.handle(processedRequest, response,
mappedHandler.getHandler()); applyDefaultViewName(processedRequest, mv);
// Calling the interceptor's PostHandle method mappedHandler.applyPostHandle(processedRequest, response,
mv); }catch (Exception ex) { dispatchException = ex; }
processDispatchResult(processedRequest, response, mappedHandler, mv,
dispatchException); }catch (Exception ex) { // The interceptor will be called after an exception is thrown AfterCompletion method
triggerAfterCompletion(processedRequest, response, mappedHandler, ex); }finally
{if (asyncManager.isConcurrentHandlingStarted()) { // Instead of postHandle and
afterCompletion if (mappedHandler != null) {
// if Controller Method is called asynchronously , Then execute interceptor afterConcurrentHandlingStarted( only AsyncHandlerInterceptor Interceptors do )
mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
} } } }
2.2 Get interceptor
protected void doDispatch(HttpServletRequest request, HttpServletResponse
response)throws Exception { // return HandlerExecutionChain It contains the interceptor queue mappedHandler
= getHandler(processedRequest); }// return HandlerExecutionChain public final
HandlerExecutionChaingetHandler(HttpServletRequest request) throws Exception {
HandlerExecutionChain executionChain = getHandlerExecutionChain(handler,
request);return executionChain; } protected HandlerExecutionChain
getHandlerExecutionChain(Object handler, HttpServletRequest request) {
HandlerExecutionChain chain = (handlerinstanceof HandlerExecutionChain ?
(HandlerExecutionChain) handler :new HandlerExecutionChain(handler));
// according to url And interceptor exception configuration url Make a comparison , Join the queue if it meets String lookupPath = this
.urlPathHelper.getLookupPathForRequest(request);for (HandlerInterceptor
interceptor :this.adaptedInterceptors) { if (interceptor instanceof
MappedInterceptor) { MappedInterceptor mappedInterceptor = (MappedInterceptor)
interceptor;if (mappedInterceptor.matches(lookupPath, this.pathMatcher)) {
chain.addInterceptor(mappedInterceptor.getInterceptor()); } }else {
chain.addInterceptor(interceptor); } }return chain; } public boolean matches
(String lookupPath, PathMatcher pathMatcher) { PathMatcher pathMatcherToUse = (
this.pathMatcher != null) ? this.pathMatcher : pathMatcher; if (this
.excludePatterns !=null) { for (String pattern : this.excludePatterns) { if
(pathMatcherToUse.match(pattern, lookupPath)) {return false; } } } if (this
.includePatterns ==null) { return true; } else { for (String pattern : this
.includePatterns) {if (pathMatcherToUse.match(pattern, lookupPath)) { return
true; } } return false; } }
Information of the above interceptor , All from the configuration file below
<!-- Interceptor chain --> <mvc:interceptors> <mvc:interceptor> <!-- Interceptor mapping The interceptor will only be executed if it conforms to the -->
<mvc:mapping path="/**"/> <!-- In the interceptor mapping Remove the following url --> <mvc:exclude-mapping path
="/transactional_test/*"/> <!-- Interceptor executed --> <ref bean="apiInterceptor"/> </
mvc:interceptor> </mvc:interceptors> <bean id="apiInterceptor" class=
"com.lk.dome.interceptor.ApiInterceptor"/>
2.3 Workflow Interceptor
boolean applyPreHandle(HttpServletRequest request, HttpServletResponse
response)throws Exception { HandlerInterceptor[] interceptors =
getInterceptors();if (!ObjectUtils.isEmpty(interceptors)) { for (int i = 0; i <
interceptors.length; i++) { HandlerInterceptor interceptor = interceptors[i];
// If back false, Then directly execute the interceptor's triggerAfterCompletion method if
(!interceptor.preHandle(request, response,this.handler)) {
triggerAfterCompletion(request, response,null); // Direct return , In the outer layer doDispatch Do not execute the following logic in the logic
return false; } // Record the number of interceptors executed successfully this.interceptorIndex = i; } } return true; }
void applyPostHandle(HttpServletRequest request, HttpServletResponse response,
ModelAndView mv)throws Exception { HandlerInterceptor[] interceptors =
getInterceptors();if (!ObjectUtils.isEmpty(interceptors)) { // Interceptor queue from back to front , In reverse order
for (int i = interceptors.length - 1; i >= 0; i--) { HandlerInterceptor
interceptor = interceptors[i]; interceptor.postHandle(request, response,this
.handler, mv); } } }void triggerAfterCompletion(HttpServletRequest request,
HttpServletResponse response, Exception ex)throws Exception {
HandlerInterceptor[] interceptors = getInterceptors();if
(!ObjectUtils.isEmpty(interceptors)) {//interceptorIndex Interceptor flag for successful execution for (int i =
this.interceptorIndex; i >= 0; i--) { HandlerInterceptor interceptor =
interceptors[i];try { interceptor.afterCompletion(request, response, this
.handler, ex); }catch (Throwable ex2) { logger.error(
"HandlerInterceptor.afterCompletion threw exception", ex2); } } } }
// Asynchronous method call , Interceptor must belong to AsyncHandlerInterceptor Interface void
applyAfterConcurrentHandlingStarted(HttpServletRequest request,
HttpServletResponse response) { HandlerInterceptor[] interceptors =
getInterceptors();if (!ObjectUtils.isEmpty(interceptors)) { for (int i =
interceptors.length -1; i >= 0; i--) { if (interceptors[i] instanceof
AsyncHandlerInterceptor) {try { AsyncHandlerInterceptor asyncInterceptor =
(AsyncHandlerInterceptor) interceptors[i];
asyncInterceptor.afterConcurrentHandlingStarted(request, response,this
.handler); }catch (Throwable ex) { logger.error("Interceptor [" +
interceptors[i] +"] failed in afterConcurrentHandlingStarted", ex); } } } } }