攔截器相似於過濾器,可是攔截器提供更精細的的控制能力,它能夠在一個請求過程當中的兩個節點進行攔截:java
例如,你能夠使用攔截器在將請求發送到控制器以前添加請求頭,並在將響應發送到客戶端以前添加響應標頭。ide
建立一個攔截器,須要實現HandlerInterceptor接口,他有三個方法來完成攔截post
preHandle(): 用於在將請求發送到控制器以前執行操做。此方法應返回true以將響應返回給客戶端。學習
postHandle() :用於在將響應結果發送到客戶端以前執行操做。spa
afterCompletion() :用於在請求響應所有結束後執行以後的操做。blog
一個自定義的攔截器代碼以下:接口
@Component
public class ProductServiceInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(
HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return true;
}
@Override
public void postHandle(
HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception exception) throws Exception {}
}
攔截器完成後,必須使用WebMvcConfigurerAdapter向InterceptorRegistry註冊此Interceptor,以下所示io
@Component
public class ProductServiceInterceptorAppConfig extends WebMvcConfigurerAdapter {
@Autowired
ProductServiceInterceptor productServiceInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(productServiceInterceptor);
}
}