web开发时,通常web工程都有一个webapp目录,该目录下的静态资源可以直接访问,下面简要介绍下spring boot访问静态资源的方式!
1.最笨的方式:静态资源以流方式返回给前端(最本质的处理方式)
比如maven工程的resources根目录下建立一个html的目录,然后把静态资源文件放在该目录下,并且规定任何访问路径以/static/开头的即访问该目录下的静态资源。
@Controller
public class StaticResourceController {
@RequestMapping("/static/**") // 处理以static开头的请求
public void getHtml(HttpServletRequest request, HttpServletResponse response) {
String uri = request.getRequestURI();
String[] arr = uri.split("static/");
String resourceName = "index.html"; // 默认访问资源名
if (arr.length > 1) {
// 截取请求资源文件名
resourceName = arr[1];
}
// 寻找资源路径
String url = StaticResourceController.class.getResource("/").getPath() + "html/" + resourceName;
try {
FileReader reader = new FileReader(new File(url));
BufferedReader br = new BufferedReader(reader);
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
// 数据直接以流的方式返回
response.getOutputStream().write(sb.toString().getBytes());
response.flushBuffer();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.Spring boot默认静态资源访问方式
Spring boot默认可以直接访问四个目录(目录处于src/main/resources资源目录下)下的文件:
classpath:/META-INF/resources/
classpath:/resources
classpath:/static/
classpath:/public/
其先后顺序,正是静态资源的查找顺序。 也就是说, 如果出现了多个同名的静态资源, 那么以前面找到的为准。
注意:优先顺序可以通过自定义static-locations的值来调整。
3.自定义静态资源目录
除了spring boot默认的静态资源目录,也可以自定义目录,比如所有/image/**的路径都会访问images目录下的资源
① 配置类方式,通过继承WebMvcConfigurerAdapter,重写addResourceHandlers方法,该方法专门用于处理静态资源。
@Configuration
public class ImageMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/image/**").addResourceLocations("classpath:/images/");
}
}
②application.yml中配置
spring:
mvc:
static-path-pattern: /image/**
resources:
static-locations: classpath:/images/
static-path-pattern:访问模式默认为/**,多项以逗号分隔
static-locations:资源目录,多目录以逗号分隔,默认资源目录为classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
注意:该配置会覆盖Spring boot默认的静态资源目录,如果按示例中配置,则无法再访问static、public、resources等默认目录下的资源。