SpringBoot关于默认静态资源访问路径定义及自定义设置

Spring Boot 对静态资源映射提供了默认配置, 默认将 /** 所有访问映射到以下目录:

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

classpath 即WEB-INF下面的classes目录,在springboot项目中可能就是src/main/resources目录。

也就是\resources目录下默认上面三个目录:static,public,resources均可以无需任何配置浏览器直接访问到。

正常情况下,我们只需要将我们的静态资源放到src/main/resource/static这个目录下即可正常访问,也不需要额外再去创建其他静态资源目录,但是如果我们想自定义一下目录,则可以在application.properties添加spring.resources.static-locations:来指定位置

spring.resources.static-locations:的默认值是:

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

如果我们想将html页面资源放在src/main/resource/webapp下,只需设置spring.resources.static-locations=classpath:/webapp/,即可直接访问到,但是会覆盖前面的四条设置。所以直接在后面追加一条即可。

像这样:

spring.web.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/webapp/

当然你也可以直接指定一个硬盘上的任意目录:

#自定义的属性,指定了一个路径,注意要以/结尾
upload-path=D:/verifies/
#会覆盖默认配置,所以需要将默认的也加上否则static、public等这些默认静态资源路径将不能再被使用
spring.web.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/webapp/,file:${upload-path}

当然也可以通过代码在java类中指定,一般不推荐,配置文件指定更加简单高效

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        if(!registry.hasMappingForPattern("/static/**")){
            registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        }
        super.addResourceHandlers(registry);
    }

}

  • 9
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值