SpringBoot 处理静态资源

来源:互联网 发布:java招聘网站源码 编辑:程序博客网 时间:2024/05/16 14:21

SpringBoot 处理静态资源

@(springBoot处理静态资源)[默认和自定义]

  • SpringBoot 处理静态资源
    • 处理静态资源默认资源映射
    • 处理静态资源自定义资源映射但不影响默认资源映射
    • 处理静态资源完全自定义资源映射且默认资源映射失效

spring Boot 默认的处理方式就已经足够了,默认情况下Spring Boot 使用WebMvcAutoConfiguration中配置的各种属性。(推荐)

但是如果你想完全控制Spring MVC,你可以在@Configuration注解的配置类上增加@EnableWebMvc,增加该注解以后WebMvcAutoConfiguration中配置就不会生效,你需要自己来配置需要的每一项。这种情况下的配置方法建议参考WebMvcAutoConfiguration类。(完全自定义资源映射且默认资源映射失效)

部分配置可以在application 配置文件中(.properties 或 .yml)

如下几个例子项目的结构图:
Alt text

处理静态资源(默认资源映射)

其中默认配置的 /** 映射到 /static (或/public、/resources、/META-INF/resources)
其中默认配置的 /webjars/** 映射到 classpath:/META-INF/resources/webjars/

处理静态资源(自定义资源映射但不影响默认资源映射)

//即注释掉@EnableWebMvc 后就可以使用默认和自定义资源映射//eg: http://localhost:8083/folder/login.html  和 http://localhost:8083/templates/index.html 都能访问@Configuration//@EnableWebMvcpublic class ResourceHandlers extends WebMvcConfigurerAdapter {    @Override    public void addResourceHandlers(ResourceHandlerRegistry registry) {        // TODO Auto-generated method stub        registry.addResourceHandler("/folder/*").addResourceLocations("classpath:/folder/");        super.addResourceHandlers(registry);    }}//其中 addResourceLocations 的参数是动参,可以这样写 addResourceLocations(“classpath:/img1/”, “classpath:/img2/”, “classpath:/img3/”);//使用外部目录如果我们要指定一个绝对路径的文件夹(如 D:/data/api_files ),则只需要使用 addResourceLocations 指定即可。// 可以直接使用addResourceLocations 指定磁盘绝对路径,同样可以配置多个位置,注意路径写法需要加上file:registry.addResourceHandler("/api_files/**").addResourceLocations("file:D:/data/api_files");

处理静态资源(完全自定义资源映射且默认资源映射失效)

//加上@EnableWebMvc 后就完全自定义资源映射且默认资源映射失效//eg: http://localhost:8083/folder/login.html  能访问 但 http://localhost:8083/templates/index.html 不能@Configuration@EnableWebMvcpublic class ResourceHandlers extends WebMvcConfigurerAdapter {    @Override    public void addResourceHandlers(ResourceHandlerRegistry registry) {        // TODO Auto-generated method stub        registry.addResourceHandler("/folder/*").addResourceLocations("classpath:/folder/");        super.addResourceHandlers(registry);    }}
原创粉丝点击