• springboot中添加拦截器(记录)


    参考:

    If you want to keep Spring Boot MVC features and you want to add additional MVC configuration (interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc. If you wish to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter, or ExceptionHandlerExceptionResolver, you can declare a WebMvcRegistrationsAdapter instance to provide such components.

    If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc.

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

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

    总结就是:通过实现WebMvcConfigurer并添加@Configuration注解来实现自定义部分SpringMvc配置。

    1.定义一个拦截器类

    @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.定义配置类,注册拦截器

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

    3.修改下日志级别

    # 设置org.springframework包的日志级别为debug
    logging.level.org.springframework=debug

     

     

     

  • 相关阅读:
    git add用法
    git删除指定文件夹
    git相关命令
    Stacktrace: org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:5
    [程序员代码面试指南]数组和矩阵-子矩阵的最大累加和问题
    [程序员代码面试指南]二叉树问题-统计完全二叉树的节点数
    [排序]直接插入排序、希尔排序
    [程序员代码面试指南]判断字符数组中是否所有字符只出现一次(堆排序)
    [SpringBoot项目]笔记
    [计算机网络]知识点
  • 原文地址:https://www.cnblogs.com/zxh06820/p/12903075.html
Copyright © 2020-2023  润新知