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