HandlerInterceptor與WebRequestInterceptor的異同


相同點
兩個接口都可用於Contrller層請求攔截,接口中定義的方法作用也是一樣的。

//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;

//WebRequestInterceptor
void preHandle(WebRequest request) throws Exception;
void postHandle(WebRequest request, ModelMap model) throws Exception;
void afterCompletion(WebRequest request, Exception ex) throws Exception;
WebRequestInterceptor間接實現了HandlerInterceptor,只是他們之間使用WebRequestHandlerInterceptorAdapter適配器類聯系。

不同點
WebRequestInterceptor的入參WebRequest是包裝了HttpServletRequest 和HttpServletResponse的,通過WebRequest獲取Request中的信息更簡便。
2.WebRequestInterceptor的preHandle是沒有返回值的,說明該方法中的邏輯並不影響后續的方法執行,所以這個接口實現就是為了獲取Request中的信息,或者預設一些參數供后續流程使用。
3.HandlerInterceptor的功能更強大也更基礎,可以在preHandle方法中就直接拒絕請求進入controller方法。
使用場景
這個在上條已經說了,如果想更方便獲取HttpServletRequest的信息就使用WebRequestInterceptor,當然這些HandlerInterceptor都能做,只不過要多寫點代碼

如何配置
配置類繼承WebMvcConfigurationSupport或WebMvcConfigurerAdapter類,重寫addInterceptors,InterceptorRegistry實例就可以直接添加。
順便說下繼承WebMvcConfigurationSupport或WebMvcConfigurerAdapter的區別,繼承WebMvcConfigurationSupport不需要聲明@EnableWebMvc注解,繼承WebMvcConfigurerAdapter需要


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM