是SpringFramework爲咱們提供的攔截器,通常咱們能夠用來鑑權或者日誌記錄等。java
它是一個interface,主要方法有:spring
/** * Intercept the execution of a handler. Called after HandlerMapping determined * an appropriate handler object, but before HandlerAdapter invokes the handler. * <p>DispatcherServlet processes a handler in an execution chain, consisting * of any number of interceptors, with the handler itself at the end. * With this method, each interceptor can decide to abort the execution chain, * typically sending a HTTP error or writing a custom response. * @param request current HTTP request * @param response current HTTP response * @param handler chosen handler to execute, for type and/or instance evaluation * @return {@code true} true表示繼續流程(如調用下一個攔截器或處理器);false表示流程中斷 *(如登陸檢查失敗),不會繼續調用其餘的攔截器或處理器,此時咱們須要經過response來產生響應 * @throws Exception in case of errors */ boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception; /** * 後處理回調方法,實現處理器的後處理(但在渲染視圖以前),此時咱們能夠經過modelAndView(模型和視圖對象)對模型數據進行處理或對視圖進行處理,modelAndView也可能爲null。 * Intercept the execution of a handler. Called after HandlerAdapter actually * invoked the handler, but before the DispatcherServlet renders the view. * Can expose additional model objects to the view via the given ModelAndView. * <p>DispatcherServlet processes a handler in an execution chain, consisting * of any number of interceptors, with the handler itself at the end. * With this method, each interceptor can post-process an execution, * getting applied in inverse order of the execution chain. * @param request current HTTP request * @param response current HTTP response * @param handler handler (or {@link HandlerMethod}) that started async * execution, for type and/or instance examination * @param modelAndView the {@code ModelAndView} that the handler returned * (can also be {@code null}) * @throws Exception in case of errors */ void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception; /** * Callback after completion of request processing, that is, after rendering * the view. Will be called on any outcome of handler execution, thus allows * for proper resource cleanup. * <p>Note: Will only be called if this interceptor's {@code preHandle} * method has successfully completed and returned {@code true}! * <p>As with the {@code postHandle} method, the method will be invoked on each * interceptor in the chain in reverse order, so the first interceptor will be * the last to be invoked. * @param request current HTTP request * @param response current HTTP response * @param handler handler (or {@link HandlerMethod}) that started async * execution, for type and/or instance examination * @param ex exception thrown on handler execution, if any * @throws Exception in case of errors */ void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception;
preHandle 預處理回調,在處理器處理以前回調設計模式
postHandle 處理器處理完畢,在渲染以前回調,能夠計算處理器處理時間app
afterCompletion 請求渲染結束後回調 這邊咱們能夠計算渲染時間,或者整個請求的執行時間異步
有時候咱們可能只須要實現三個回調方法中的某一個,若是實現HandlerInterceptor接口的話,三個方法必須實現,無論你需不須要,此時spring提供了一個HandlerInterceptorAdapter適配器(適配器設計模式的實現),容許咱們只實現須要的回調方法。async
public abstract class HandlerInterceptorAdapter implements AsyncHandlerInterceptor { /** * This implementation always returns {@code true}. */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { return true; } /** * This implementation is empty. */ @Override public void postHandle( HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } /** * This implementation is empty. */ @Override public void afterCompletion( HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } /** * This implementation is empty. * 當Controller中有異步請求方法的時候會觸發該方法。 樓主作過測試,異步請求先支持preHandle、而後執行afterConcurrentHandlingStarted */ @Override public void afterConcurrentHandlingStarted( HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { } }
運行流程總結以下:ide
一、攔截器執行順序是按照Spring配置文件中定義的順序而定的。post
二、會先按照順序執行全部攔截器的preHandle方法,一直遇到return false爲止,好比第二個preHandle方法是return false,則第三個以及之後全部攔截器都不會執行。若都是return true,則按順序加載完preHandle方法。測試
三、而後執行主方法(本身的controller接口),若中間拋出異常,則跟return false效果一致,不會繼續執行postHandle,只會倒序執行afterCompletion方法。優化
四、在主方法執行完業務邏輯(頁面還未渲染數據)時,按倒序執行postHandle方法。若第三個攔截器的preHandle方法return false,則會執行第二個和第一個的postHandle方法和afterCompletion(postHandle都執行完纔會執行這個,也就是頁面渲染完數據後,執行after進行清理工做)方法。(postHandle和afterCompletion都是倒序執行
其實從上面的HandlerInterceptor到HandlerInterceptorAdapter,咱們能夠看出這是使用了接口適配器模式,接口Adapter對接口進行實現,可是又不作具體的邏輯實現。
這樣咱們在使用的時候只要繼承對應的Adapter複寫須要的方法便可
上面那種在Java8以前常常會用到,但是在Java8新增default方法後,就不多用到了。前提最低支持Java8
Java8的新特性中有一個新特性爲接口默認方法,該新特性容許咱們在接口中添加一個非抽象的方法實現,而這樣作的方法只須要使用關鍵字default修飾該默認實現方法便可。該特性又叫擴展方法
public interface Formula { double calculate(int a); default double sqrt(int a){ return Math.sqrt(a); } }
經過該特性,咱們將可以很方便的實現接口默認實現類。這個特性在編譯器實現的角度來講更接近於Scala的trait
若是你們有用過SpringBoot2.0會發現有大量的方法或者類被從新設計,固然一部分是對1.0的接口優化或者功能優化。
其中一個很重要的是對JDK的要求,也就是說Spring Boot2.0的最低版本要求爲JDK8。從代碼中咱們能夠看出,不少地方使用了default方法,對於老的接口Adapter進行了捨棄。
好比咱們之前在配置相應的HandlerInterceptor使用的WebMvcConfigurerAdapter,就被標記爲Deprecated
/** * An implementation of {@link WebMvcConfigurer} with empty methods allowing * subclasses to override only the methods they're interested in. * * @author Rossen Stoyanchev * @since 3.1 * @deprecated as of 5.0 {@link WebMvcConfigurer} has default methods (made * possible by a Java 8 baseline) and can be implemented directly without the * need for this adapter */ @Deprecated public abstract class WebMvcConfigurerAdapter implements WebMvcConfigurer
接下來咱們來看下WebMvcConfigurer在SpringBoot2.0和SpringBoot1.0中的代碼區別:
SpringBoot2.0中使用的SpringFramework5
public interface WebMvcConfigurer { default void configurePathMatch(PathMatchConfigurer configurer) { } default void configureContentNegotiation(ContentNegotiationConfigurer configurer) { } default void configureAsyncSupport(AsyncSupportConfigurer configurer) { } default void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { } default void addFormatters(FormatterRegistry registry) { } default void addInterceptors(InterceptorRegistry registry) { } default void addResourceHandlers(ResourceHandlerRegistry registry) { } default void addCorsMappings(CorsRegistry registry) { } default void addViewControllers(ViewControllerRegistry registry) { } default void configureViewResolvers(ViewResolverRegistry registry) { } default void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) { } default void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> handlers) { } default void configureMessageConverters(List<HttpMessageConverter<?>> converters) { } default void extendMessageConverters(List<HttpMessageConverter<?>> converters) { } default void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) { } default void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) { } @Nullable default Validator getValidator() { return null; } @Nullable default MessageCodesResolver getMessageCodesResolver() { return null; } }
SpringBoot1.0中使用的SpringFramework4
public interface WebMvcConfigurer { void addFormatters(FormatterRegistry registry); void configureMessageConverters(List<HttpMessageConverter<?>> converters); void extendMessageConverters(List<HttpMessageConverter<?>> converters); Validator getValidator(); void configureContentNegotiation(ContentNegotiationConfigurer configurer); void configureAsyncSupport(AsyncSupportConfigurer configurer); void configurePathMatch(PathMatchConfigurer configurer); void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers); void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> returnValueHandlers); void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers); void addInterceptors(InterceptorRegistry registry); MessageCodesResolver getMessageCodesResolver(); void addViewControllers(ViewControllerRegistry registry); void configureViewResolvers(ViewResolverRegistry registry); void addResourceHandlers(ResourceHandlerRegistry registry); void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer); }
其中惟一的區別就是在SpringFramework5中使用了default關鍵字,致使的結果就是WebMvcConfigurerAdapter能夠被捨棄不使用了。
固然在Spring中的例子還有不少,好比HandlerInterceptor和HandlerInterceptorAdapter等,你們在使用的時候除了要看相應的接口變化,更重要的是要去了解爲何會有這種變化
@Configuration public class WebConf implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new AsyncInterceptor()).addPathPatterns("/*"); } }