Springboot中自定義springmvc攔截器;HandlerInterceptor中preHandle,postHandle,afterCompletion解析
阿新 • • 發佈:2018-12-19
要實現自定義HandlerInterceptor 。通過 WebMvcConfigurer 的實現類屬性注入,完成springboot自定義攔截
自定義一個攔截器;
package com.baidu.interceptor;
/**
* @auther SyntacticSugar
* @data 2018/11/2 0002下午 2:51
*/
public class LoginInterceptor implements HandlerInterceptor {
private Logger logger=LoggerFactory.getLogger((LoginInterceptor. class));
// 配置一個 interceptor
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
logger.debug("preHandle is running");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
logger.debug("postHandle is running");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
logger. debug("afterCompletion is running");
}
}
注入自定義的攔截器;
package com.baidu.config;
/**
* @auther SyntacticSugar
* @data 2018/11/2 0002下午 2:49
*/
@Configuration
public class MvcConfig implements WebMvcConfigurer {
// 注入攔截器
@Bean
public LoginInterceptor getLoginInterceptor(){
return new LoginInterceptor();
}
// 把自定義的攔截器新增到mvc 配置中
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(this.getLoginInterceptor()).addPathPatterns("/**");
}
}
*訪問web伺服器; *
HandlerInterceptor 檢視原始碼如下:
(1) 第一個preHandle
default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
return true;
}
在HandlerMapping之後執行,HandlerAdapter之前,返回結果 true
(2) 第二個postHandle
default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
@Nullable ModelAndView modelAndView) throws Exception {
}
在HandlerAdapter 之後,在DispatcherServlet之前呼叫,並且通過ModelAndView 檢視解析器解析 檢視 model object;
(3) 第三個afterCompletion
default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
@Nullable Exception ex) throws Exception {
}
request處理完成之後,回撥函式,獲取解析檢視;