Spring Boot的web开发&静态资源配置方式

时间:2023-03-09 08:04:51
Spring Boot的web开发&静态资源配置方式

Web开发的自动配置类:org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration

Spring Boot的web开发&静态资源配置方式

  

1.1. 自动配置的ViewResolver(SpringMVC的视图解析器)

Spring Boot的web开发&静态资源配置方式

视图的配置mvcProperties对象中:(配置view的前缀后缀,可以在全局的application.properties中配置)

org.springframework.boot.autoconfigure.web.WebMvcProperties.View

Spring Boot的web开发&静态资源配置方式

1.2 自动配置静态资源

如果进入SpringMVC的规则为/时,Spring Boot的默认静态资源的路径为:

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

测试:

1. 未加上静态资源的配置,此时可以随便访问:

(0)目录:

Spring Boot的web开发&静态资源配置方式

(1)application.properties

server.port=80
server.serverlet-path=*.html logging.level.org.springframework=DEBUG

此时可以访问静态资源成功,访问动态资源也成功:

(1)访问静态资源:

Spring Boot的web开发&静态资源配置方式

(2)访问动态资源

Spring Boot的web开发&静态资源配置方式

2.加上静态资源的配置,此时访问项目静态资源会报资源找不见错误:

(0)目录结构:

Spring Boot的web开发&静态资源配置方式

(1)application.properties

server.port=80
server.serverlet-path=*.html logging.level.org.springframework=DEBUG
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/

 (2)访问动态资源:

Spring Boot的web开发&静态资源配置方式

(3)访问静态资源报错:

Spring Boot的web开发&静态资源配置方式

(4)解决办法:修改目录结构

Spring Boot的web开发&静态资源配置方式

启动测试:

Spring Boot的web开发&静态资源配置方式

1.3  进入规则为*.xxx 或者/,  (不指定静态文件路径时可通过路径访问静态资源)

将静态资源放置到webapp下的static目录中即可通过地址访问:

(1)目录结构

Spring Boot的web开发&静态资源配置方式

(2)配置文件:

server.port=80
server.serverlet-path=*.html logging.level.org.springframework=DEBUG

或者:

server.port=80
server.serverlet-path=/ logging.level.org.springframework=DEBUG

(3)测试:

Spring Boot的web开发&静态资源配置方式

补充:关于静态资源的方式:

#设定静态文件路径,js,css等
spring.mvc.static-path-pattern=/static/**
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/

如下配置:

spring.mvc.static-path-pattern: 是告诉springboot什么样的请求是静态请求,也就是不经过后台。换句话说,只有静态资源满足什么样的匹配条件,Spring Boot才会处理静态资源请求。
spring.resources.static-locations: 用于告诉Spring Boot应该在何处查找静态资源文件,这是一个列表性的配置,查找文件时会依赖于配置的先后顺序依次进行。上面的也是默认值。