SpringBoot快速入门-Web应用静态资源配置

如果是前后端分离的项目,则不需要引入,如果前后端都使用SpringBoot来实现,则需要引入模板引擎。
目前的模板引擎有Velocity、Freemarker、Thymeleaf。而SpringBoot推荐的Thymeleaf:语法更简单,功能更强大。

静态资源映射路径
默认情况下SpringBoot项目静态资源路径可以放在/static 或 /public 或 /resources 或 /META-INF/resources这几个目录下,并且这几个目录可以同时存在,同时使用。
默认情况下,静态资源放在这几个目录,使用 项目地址:端口/项目名称/静态资源名称 就可以直接访问静态资源。
但是很多时候,静态资源可能会和Controller访问地址发生冲突,此时项目默认会解析到Controller,静态资源则无法访问了,或者更多时候我们想做过滤器,给静态资源添加上前缀,统一跳过不做限制,此时可以通过配置完成。

Properties
spring.mvc.static-path-pattern=/resources/**

Yaml
spring:
  mvc:
  static-path-pattern: "/resources/**"

添加了上面的配置,访问静态资源路径就编程了 项目地址:端口/项目名称/resources/静态资源名称

如果你想修改静态资源放置的目录,不使用上面提供的默认目录,也是可以的,通过如下配置:spring.web.resources.staticlocations,例如:
spring.web.resources.staticlocations=/itzhimei/static/

其中要注意的点是如果同时配置了static-path-pattern和staticlocations,那么index欢迎页此时就无法访问了,这可能是SpringBoot的一个bug。所以如果要使用index,怎么这两个配置只能自定义一个。

我们看一下 官方解释:

By default, Spring Boot serves static content from a directory called /static (or /public or
/resources or /META-INF/resources) in the classpath or from the root of the ServletContext. It uses
the ResourceHttpRequestHandler from Spring MVC so that you can modify that behavior by adding
your own WebMvcConfigurer and overriding the addResourceHandlers method.

In a stand-alone web application, the default servlet from the container is also enabled and acts as
a fallback, serving content from the root of the ServletContext if Spring decides not to handle it.
Most of the time, this does not happen (unless you modify the default MVC configuration), because
Spring can always handle requests through the DispatcherServlet.

By default, resources are mapped on /, but you can tune that with the spring.mvc.static-pathpattern property. For instance, relocating all resources to /resources/ can be achieved as follows:

Properties
spring.mvc.static-path-pattern=/resources/**

Yaml
spring:
  mvc:
  static-path-pattern: "/resources/**"

You can also customize the static resource locations by using the spring.web.resources.staticlocations property (replacing the default values with a list of directory locations). The root Servlet
context path, “/”, is automatically added as a location as well.