springboot的拦截器
Posted bozhengheng
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot的拦截器相关的知识,希望对你有一定的参考价值。
首先要写一个自己的拦截器,实现HandlerInterceptor接口,并且实现接口中的三个方法,同时添加 @Component 注解,把自己的拦截器放入容器 中管理,方便以后的注入使用。
@Component public class MyIntercepor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("前值方法"); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("后置方法"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("完成方法"); } }
然后要写一个配置类,用来添加拦截器到 配置类中,让拦截器启用,因为使用的是springboot所以配置类要 使用@Configuration注解,标明本类是配置类
并且要继承WebMvcConfigurer这个接口,并且注入自己写的拦截器,并且从写public void addInterceptors(InterceptorRegistry registry)这个方法,注册自己写的拦截器,
@Configuration public class MyWebMvcConfig implements WebMvcConfigurer { @Autowired private MyIntercepor myIntercepor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(myIntercepor).addPathPatterns("/**"); } }
结果
2020-05-01 17:40:41.708 DEBUG 9812 --- [nio-8888-exec-1] o.s.b.f.s.DefaultListableBeanFactory : Returning cached instance of singleton bean ‘userController‘ 2020-05-01 17:40:41.709 DEBUG 9812 --- [nio-8888-exec-1] o.s.web.servlet.DispatcherServlet : Last-Modified value for [/user/hello] is: -1 前值方法 2020-05-01 17:40:41.764 DEBUG 9812 --- [nio-8888-exec-1] m.m.a.RequestResponseBodyMethodProcessor : Written [this is hello controller] as "text/html" using [org.springframework.http.converter.StringHttpMessageConverter@31ceba99] 后置方法 2020-05-01 17:40:41.766 DEBUG 9812 --- [nio-8888-exec-1] o.s.web.servlet.DispatcherServlet : Null ModelAndView returned to DispatcherServlet with name ‘dispatcherServlet‘: assuming HandlerAdapter completed request handling 完成方法 2020-05-01 17:40:41.766 DEBUG 9812 --- [nio-8888-exec-1] o.s.web.servlet.DispatcherServlet : Successfully completed request 2020-05-01 17:40:41.767 DEBUG 9812 --- [nio-8888-exec-1] o.s.b.w.s.f.OrderedRequestContextFilter : Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade@388e5df3
以上是关于springboot的拦截器的主要内容,如果未能解决你的问题,请参考以下文章
Java 微服务 day02 源代码 SpringBoot 实战开发 SpringMVC高级配置:拦截器:HandlerExecutionChain
SpringBoot拦截器----addInterceptors