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);
    }
  • 相关阅读:
    discuz 帖子模块用到的表及自动发帖函数
    【转】php json_encode中文为空的解决办法
    linux自定义脚本添加到rc.local脚本无法正常运行的问题
    【转】实战 SSH 端口转发
    linux shell脚本守护进程监控svn服务
    解决ecshop登陆自动退出的莫名现象
    windows下不打开浏览器访问网页的方法
    【转】windows下安装和调用curl的方法
    调用discuz编辑器发布帖子显示html代码的解决办法
    linux下搭建svn版本控制软件
  • 原文地址:https://www.cnblogs.com/frank2015/p/9479609.html
Copyright © 2011-2022 走看看