zoukankan      html  css  js  c++  java
  • spring boot 添加拦截器

    如果你想要保持Spring Boot 的一些默认MVC特征,同时又想自定义一些MVC配置(包括:拦截器,格式化器, 视图控制器、消息转换器 等等),你应该让一个类实现WebMvcConfigurer,并且添加@Configuration注解,但是千万不要@EnableWebMvc注解。如果你想要自定义HandlerMappingHandlerAdapterExceptionResolver等组件,你可以创建一个WebMvcRegistrationsAdapter实例 来提供以上组件。

    如果你想要完全自定义SpringMVC,不保留SpringBoot提供的一切特征,你可以自己定义类并且添加@Configuration注解和@EnableWebMvc注解

     

    定义一个拦截器 

    @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!");
        }
    }

     定义配置类  注册拦截器 

    @Configuration
    public class MvcConfiguration implements WebMvcConfigurer {
    
        @Autowired
        private HandlerInterceptor myInterceptor;
    
        /**
         * 重写接口中的addInterceptors方法,添加自定义拦截器
         * @param registry
         */
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(myInterceptor).addPathPatterns("/**");
        }
    }

      

    运行 查看日志 

    springMVC记录的log级别是debug,springboot默认是显示info以上,我们需要进行配置。

    SpringBoot通过logging.level.*=debug来配置日志级别,*填写包名

    # 设置org.springframework包的日志级别为debug
    logging.level.org.springframework=debug
  • 相关阅读:
    JSP内置对象
    Angular $scope和$rootScope事件机制之$emit、$broadcast和$on
    Ionic开发实战
    Entity Framework 5.0 Code First全面学习
    6个强大的AngularJS扩展应用
    使用npm安装一些包失败了的看过来(npm国内镜像介绍)
    自己家里搭建NAS服务器有什么好方案?
    自己动手制作CSharp编译器
    使用Visual Studio Code搭建TypeScript开发环境
    Office web app server2013详细的安装和部署
  • 原文地址:https://www.cnblogs.com/qin1993/p/12639481.html
Copyright © 2011-2022 走看看