zoukankan      html  css  js  c++  java
  • SpringBoot学习之路踩坑系列:访问静态资源

    众所周知,SpringBoot的静态资源默认路径定义在

    org.springframework.boot.autoconfigure.web.ResourceProperties

    1 private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
    2             "classpath:/META-INF/resources/", "classpath:/resources/",
    3             "classpath:/static/", "classpath:/public/" };


    不能访问静态资源的原因:

    1. 使用@EnableWebMvc:

    启用Spring MVC pattern,这时SpringBoot的默认配置就不生效了,静态资源需要放在webapp目录下

    2. 配置拦截器

    2.1 继承WebMvcConfigurationSupport

    在spring boot的自定义配置类继承 WebMvcConfigurationSupport 后,发现自动配置的静态资源路径(classpath:/META/resources/,classpath:/resources/,classpath:/static/,classpath:/public/)不生效。

     WebMvcAutoConfiguration 有如下注解:

    @Configuration
    @ConditionalOnWebApplication
    @ConditionalOnClass({ Servlet.class, DispatcherServlet.class,
        WebMvcConfigurerAdapter.class })
    @ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
    @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
    @AutoConfigureAfter({ DispatcherServletAutoConfiguration.class,
        ValidationAutoConfiguration.class })

    这个注解的意思是在项目类路径中 缺少 WebMvcConfigurationSupport类型的bean时该自动配置类WebMvcAutoConfiguration才会生效,所以继承 WebMvcConfigurationSupport 后需要自己再重写相应的方法。

    如果想要使用自动配置生效,又要按自己的需要重写某些方法,比如增加 viewController ,则可以自己的配置类可以继承  WebMvcConfigurerAdapter 这个类。不过在spring5.0版本后这个类被丢弃了 WebMvcConfigurerAdapter  ,虽然还可以用,但是看起来不好 = =。

     重写示例:

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/META-INF/resources/")
                .addResourceLocations("classpath:/resources/")
                .addResourceLocations("classpath:/static/")
                .addResourceLocations("classpath:/public/");
        super.addResourceHandlers(registry);
    }
  • 相关阅读:
    jquery实现checkbox列表的全选不选
    SQL server 无法更新标识列
    如何设置IIS程序池的回收时间,才能最大程度的减少对用户的影响?
    混合式App开发 Apicloud 官方iPhone X 适配
    C# 加密解密以及sha256不可逆加密案例
    C#排队处理DEMO
    vs中如何统计整个项目的代码行数
    ApiCloud利用NVTabBar模块快速搭建起APP的框架
    走进异步编程的世界--async/await项目使用实战
    H5开发APP考题和答案
  • 原文地址:https://www.cnblogs.com/frank2015/p/9479609.html
Copyright © 2011-2022 走看看