Interceptor Interceptor for interceptionController Layer interface, It's kind of likeSpring OfAOP, howeverAOP For a single approach.Interceptor Aimed atController Interface and can handlerequest andresponse object.

1 HandlerInterceptor Definition of interface

Let's see firstHandlerInterceptor Definition of interface, Three interfaces are defined, NamelypreHandle,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 calledController Previously called, When returnfalse after, Will skip subsequent interceptors, And will not execute all interceptorspostHandle, And call returntrue Of the interceptorafterCompletion Method.
postHandle Is calledController Later called, But in renderingView Before page.

afterCompletion Is the end of the call.Controller Interface, RenderingView Last page call. Returntrue All interceptors of will call the interceptorafterCompletion Method, Contrary order.


andHandlerInterceptor It's very similar to having oneAsyncHandlerInterceptor Interface, It's just one moreafterConcurrentHandlingStarted One way, 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 indoDispatch Main processing logic

DispatcherServlet indoDispatch() NamelyspringMVC 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 { //....... Ellipsis code // ReturnHandlerExecutionChain
It contains the interceptor queue mappedHandler = getHandler(processedRequest);
// Call interceptorPreHandle Method, If returnsfalse Non executionController logic, Do not callPostHandle Method if
(!mappedHandler.applyPreHandle(processedRequest, response)) {return; } //
HandleController layer mv = ha.handle(processedRequest, response,
mappedHandler.getHandler()); applyDefaultViewName(processedRequest, mv);
// Calling the interceptor'sPostHandle 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 thrownAfterCompletion Method
triggerAfterCompletion(processedRequest, response, mappedHandler, ex); }finally
{if (asyncManager.isConcurrentHandlingStarted()) { // Instead of postHandle and
afterCompletion if (mappedHandler != null) {
// ifController Method is called asynchronously, Then execute interceptorafterConcurrentHandlingStarted( onlyAsyncHandlerInterceptor Interceptors do)
mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
} } } }
2.2 Get interceptor
protected void doDispatch(HttpServletRequest request, HttpServletResponse
response)throws Exception { // ReturnHandlerExecutionChain It contains the interceptor queue mappedHandler
= getHandler(processedRequest); }// ReturnHandlerExecutionChain 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 tourl And interceptor exception configurationurl Contrast, 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> <!-- Interceptormapping The interceptor will only be executed if it conforms to the-->
<mvc:mapping path="/**"/> <!-- Interceptormapping Remove the followingurl --> <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 returnsfalse, Then directly execute the interceptor'striggerAfterCompletion Method if
(!interceptor.preHandle(request, response,this.handler)) {
triggerAfterCompletion(request, response,null); // Direct return, Outer layerdoDispatch 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, Contrary 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 toAsyncHandlerInterceptor 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); } } } } }