SpringBoot加载静态资源的问题

本文详细解析了SpringBoot中静态资源的配置方法,包括spring.mvc.view.prefix、spring.mvc.view.suffix、spring.mvc.static-path-pattern及spring.resources.static-locations的作用与使用场景。通过实例展示了如何配置这些选项来正确加载静态资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SpringBoot在加载静态资源时,与之相关的配置项主要有四个

spring.mvc.view.prefix=/static/
spring.mvc.view.suffix=.html
spring.mvc.static-path-pattern=/static/**
spring.resources.static-locations=classpath:/static/page/

其中:

1. spring.mvc.view.prefix和spring.mvc.view.suffix两者是前缀与后缀,需要注意的是,这里说的前缀与后缀是相对于Controller层返回的String或者ModelAndView里面的viewName的。例如,配置文件用的是上面的配置文件,Controller层如下:

@Controller
@RequestMapping("/page")
public class PageController
{
    @RequestMapping("/index")
    public String index(){
        return "index2";
    }
}

此时,会返回的是存储静态资源目录下的static目录下的index2.html文件。

2.spring.resources.static-locations: 这个就是配置上面讲的静态资源配置目录,在SpringBoot启动的时候会去应用它配置目录,默认值是:classpath:/static,classpath:/public,classpath:/resources,classpath:/META-INF/resources,servlet context:/,可参见ResourceProperties类代码,如下:

注:classpath:是指web-inf下classes目录(SpringBoot应该是target下的classes,详见https://www.jianshu.com/p/3f61ac9b0ec2)。

3.spring.mvc.static-path-pattern: 表z示当你的路径中存在此标记的时候才会访问此静态资源。但这里有一个问题,这里将的路径网上的资料一般都说的是指浏览器中的url,但是我发现貌似写在spring.mvc.view.prefix中也可以,这种情况如下图所示:

配置如下:

spring.mvc.view.prefix=/static/
spring.mvc.view.suffix=.html
spring.mvc.static-path-pattern=/static/**

访问url:http://localhost:8090/page/index

Controller代码:

@Controller
@RequestMapping("/page")
public class PageController
{
    @RequestMapping("/index")
    public String index(){
        return "index2";
    }
}

 

访问结果:(成功找到静态页面)

但是实际上prefix是在url匹配到Handle之后才给Controller方法的返回值加上的。查看AbstractUrlHandleMapping,可以看到lookHandle方法被调用了两次,如下图所示

第一次调用,参数为url中截取的/page/index

匹配到Controller里的方法,返回String

第二次匹配, 参数为prefix+返回值+suffix

这里不知道是不是这个pattern配置项是不是设定就是这样,无论是url符合或者Controller返回的viewName匹配都可以?如果有大佬知道的话,求大佬解惑。

 

参考:

https://www.cnblogs.com/gu-bin/p/11129066.html

https://blog.youkuaiyun.com/sss996/article/details/95336876

https://blog.youkuaiyun.com/blueboz/article/details/81840593

https://www.bbsmax.com/A/E35pl8gY5v/

https://www.cnblogs.com/hujunzheng/p/9682960.html

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值