zoukankan      html  css  js  c++  java
  • SpringBoot访问静态资源和配置springMVC拦截器

    现在,我们的项目是一个jar工程,那么就没有webapp,我们的静态资源该放哪里呢?

    默认的静态资源路径为:

      - classpath:/META-INF/resources/
      - classpath:/resources/
      - classpath:/static/
      - classpath:/public/

      只要静态资源放在这些目录中任何一个,SpringMVC都会帮我们处理。

    添加拦截器:拦截器也是我们经常需要使用的,在SpringBoot中该如何配置呢?

      通过实现`WebMvcConfigurer`并添加`@Configuration`注解来实现自定义部分SpringMvc配置。

      首先我们定义一个拦截器:

    @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("/**");
      }
    }

      接下来运行并查看日志:

        preHandle method is running!
        postHandle method is running!
        afterCompletion method is running!

        会发现日志中只有这些打印信息,springMVC的日志信息都没有,因为springMVC记录的log级别是debug,springboot默认是显示info以上,我们需要进行配置。

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

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

  • 相关阅读:
    QT自定义信号和槽
    C++中深入理解dynamic_cast
    C++中rapidxml用法
    VS2015 创建C++动态库及使用
    C++ 已知两个时间(年月日)求日期差
    Electron 打开开发者工具 devtools
    NSIS安装或卸载时检查程序是否正在运行
    sqlite3 读写锁
    CEF 远程调试
    linux缩减分区空间,用以安装win系统
  • 原文地址:https://www.cnblogs.com/roadlandscape/p/12394966.html
Copyright © 2011-2022 走看看