SpringBoot 配置静态资源映射

SpringBoot 配置静态资源映射

(嵌入式servlet容器)先决知识

  1. request.getSession().getServletContext().getRealPath("/"),这个很重要,将其称为 docBase,即 “文档基目录”
  2. 在单模块项目中,如果不存在 src/main/webapp 目录,则 docBase 被设置为C盘下临时的随机目录,例如 C:\Users\Administrator\AppData\Local\Temp\tomcat-docbase.2872246570823772896.8080\
  3. 在多模块项目中,要留意jvm启动路径。无论该启动路径是位于父模块的路径下还是子模块的,如果jvm启动路径下不存在 src/main/webapp 目录,则 docBase 被设置为C盘下临时的随机目录

综上,如果想要依照传统方式通过“文档基目录”去定位文档资源(html、css、js),则要确保存在 src/main/webapp 目录,即 docBase 不会被设置为随机目录;否则,建议直接设置 SpringBoot 将其定位至 classpath 下的资源(即 src/main/resource 目录下的资源),具体配置如下

1.当不存在 @EnableWebMVC 时

  1. SpringBoot 的 @EnableAutoConfiguration 会启用自动配置类 WebMvcAutoConfiguration,该类配置了一些默认的静态资源映射
    • 自动映射 localhost:8080/** 为以下路径
      • classpath:/resources/
      • classpath:/static/
      • classpath:/public/
      • classpath:/META-INF/resources/
    • 自动映射 localhost:8080/webjars/** 为以下路径
      • classpath:/META-INF/resources/webjars/
  2. 此时,我们不需要多做什么,只要将静态资源放入 src/main/resources 目录下的 resources、static 或 public 文件夹下,即可通过 url 定位相关资源,例如 localhost:8080/index.html 可定位至 src/main/resources/static/index.html
  3. 注意:如果编写了以下的自定义配置,则以上默认配置将被取消。更确切的说,一旦自定义的配置不为空,则默认配置将不被采用。
@Configuration
public class GoWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //配置静态资源处理
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/resources2/", "classpath:/static2/", 
                "classpath:/public2/", "file:///tmp/webapps/");
    }
}

如果不喜欢代码配置,也可采取以下属性配置方式:

spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,\
  classpath:/static/,classpath:/public/,file:D://hehe

附,有一个不常用的相关属性如下

//默认值,URL访问采用 /**
spring.mvc.static-path-pattern=/**

//URL访问必须采用 /pomer/** 的形式
spring.mvc.static-path-pattern=/pomer/**

//URL访问必须采用 /12345/** 的形式
spring.mvc.static-path-pattern=/12345/**

2.当存在 @EnableWebMVC 时

  1. 如果使用了 @EnableWebMvc,则自动配置类 WebMvcAutoConfiguration 会失效,因此默认映射路径 /static, /public, META-INF/resources, /resources 都将失效
  2. 这种情况下,只能设置自定义配置
    • 无任何前缀 -> “文档根目录”(一般指代 src/main/webapp 目录), 例如 localhost:8080/index.html 定位至 src/main/webapp/static/index.html
    • 存在前缀 classpath -> 类路径(一般指代 src/main/resources 目录)
    • 存在前缀 file:// -> 文件系统路径(“绝对路径”)
@Configuration
public class GoWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //配置静态资源处理
        registry.addResourceHandler("/**")
                .addResourceLocations("resources/", "static/", "public/", 
                "META-INF/resources/")
                .addResourceLocations("classpath:resources/", "classpath:static/", 
                "classpath:public/", "classpath:META-INF/resources/")
                .addResourceLocations("file:///tmp/webapps/");
    }
}

猜你喜欢

转载自www.cnblogs.com/pomer-huang/p/pomer.html
今日推荐