相同點(diǎn)
兩個(gè)接口都可用于Contrller層請(qǐng)求攔截,接口中定義的方法作用也是一樣的。
//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間接實(shí)現(xiàn)了HandlerInterceptor,只是他們之間使用WebRequestHandlerInterceptorAdapter適配器類聯(lián)系。
不同點(diǎn)
- WebRequestInterceptor的入?yún)ebRequest是包裝了HttpServletRequest 和HttpServletResponse的,通過WebRequest獲取Request中的信息更簡(jiǎn)便。
2.WebRequestInterceptor的preHandle是沒有返回值的,說明該方法中的邏輯并不影響后續(xù)的方法執(zhí)行,所以這個(gè)接口實(shí)現(xiàn)就是為了獲取Request中的信息,或者預(yù)設(shè)一些參數(shù)供后續(xù)流程使用。
3.HandlerInterceptor的功能更強(qiáng)大也更基礎(chǔ),可以在preHandle方法中就直接拒絕請(qǐng)求進(jìn)入controller方法。
使用場(chǎng)景
這個(gè)在上條已經(jīng)說了,如果想更方便獲取HttpServletRequest的信息就使用WebRequestInterceptor,當(dāng)然這些HandlerInterceptor都能做,只不過要多寫點(diǎn)代碼
如何配置
配置類繼承WebMvcConfigurationSupport或WebMvcConfigurerAdapter類,重寫addInterceptors,InterceptorRegistry實(shí)例就可以直接添加。
順便說下繼承WebMvcConfigurationSupport或WebMvcConfigurerAdapter的區(qū)別,繼承WebMvcConfigurationSupport不需要聲明@EnableWebMvc注解,繼承WebMvcConfigurerAdapter需要