声明,使用 JDK8 、maven3.5.4 、idea2018
1、自定义拦截器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");
}
}
2、注入自定义的拦截器,
通过@Configuration声明配置类,实现WebMvcConfigurer 接口中的 addInterceptors()添加自定义的拦截器;*
register里面有两个方法,addInterceptor(HandlerInterceptor interceptor) 参数为HandlerInterceptor ,自定义的拦截器实现的是 HandlerInterceptor接口;所以使用 第一个方法添加拦截器;*
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("/**");
}
}
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 {
}
小结:
springboot中添加 自定义的springmvc拦截器,不同于springmvc中添加自定义拦截器;
但是大体步骤都是一样的,1,自定义一个拦截器;2,把拦截器添加到springmvc的配置;
springmvc中添加一个自定义拦截器,是把自定义拦截器通过xml配置,配置到核心配置文件springmvc-servlet.xml中;
具体参考如下:
https://blog.csdn.net/weixin_42323802/article/details/84141617