SpringBoot自定义配置拦截器
程序员文章站
2022-07-03 20:07:01
...
1.自定义拦截器实现HandlerInterceptor接口
@Component
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle method is running!");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle method is running!");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion method is running!");
}
}
2.配置拦截器:自定义一个java配置类(@Configuration),实现WebMvcConfigurer接口
@Configuration
public class MvcConfig implements WebMvcConfigurer {
@Autowired
private HandlerInterceptor myInterceptor;
/**
* 重写接口中的addInterceptors方法,添加自定义拦截器
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor).addPathPatterns("/**");
}
}
上一篇: Maven中传JSON转换所需的依赖
下一篇: logBack配置文件