Spring Boot 默认为我们提供了静态资源处理,使用 WebMvcAutoConfiguration 中的配置各种属性。建议大家使用Spring Boot的默认配置方式,提供的静态资源映射如下:
classpath:/META-INF/resources
classpath:/resources
classpath:/static
classpath:/public
在工程里面路径是这样:
上面这几个都是静态资源的映射路径,优先级顺序为:
META-INF/resources > resources > static > public
可以直接访问:http://www.javashuo.com/tag/http://localhost:8080
2.配置路径
对应的配置为:
# 默认值为 /**
spring.mvc.static-path-pattern=
# 默认值为 classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
spring.resources.static-locations=这里设置要指向的路径,多个使用英文逗号隔开
如,我们添加配置:
spring.mvc.static-path-pattern=/gary/**
只能访问:http://localhost:8080/gary/index.html
举个例子:如果想自定义一个路径,页面访问时为my,工程目录为myresource,配置如下:
spring.mvc.static-path-pattern=/my/**
spring.resources.static-locations=classpath:/myresources/
创建目录,放一张图片:
访问:
定义一个配置类并继承WebMvcConfigurerAdapter。想自定义静态资源映射目录的话,只需重写addResourceHandlers方法即可。
package com.ConfigurerAdapter;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class MyWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter{
/**
* 配置静态访问资源
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/my/**").addResourceLocations("classpath:/myresources/");
super.addResourceHandlers(registry);
}
}
如果你想指定外部的目录也很简单,直接addResourceLocations指定即可,代码如下:
registry.addResourceHandler("/my/**").addResourceLocations("file:d:/myresources/");
addResourceLocations指的是文件放置的目录,addResoureHandler指的是对外暴露的访问路径。