静态资源访问
2023年11月17日大约 3 分钟约 533 字
官方文档
在线文档:https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.developing-web-applications
基本介绍
- 只要静态资源放在类路径下: /static 、 /public 、 /resources 、 /META-INF/resources 可以被直接访问- 对应文件 WebProperties.java

- 常见静态资源:JS、CSS 、图片(.jpg .png .gif .bmp .svg)、字体文件(Fonts)等
- 访问方式:默认: 项目根路径/ + 静态资源名 比如 http://localhost:8080/hi.jpg - 设置 WebMvcProperties.java

快速入门
创建 SpringBoot 项目 springbootweb
配置 pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.lzw</groupId>
<artifactId>springbootweb</artifactId>
<version>1.0-SNAPSHOT</version>
<!--导入springboot父工程-规定写法-->
<parent>
<artifactId>spring-boot-starter-parent</artifactId>
<groupId>org.springframework.boot</groupId>
<version>2.5.3</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
创建 src/main/java/com/lzw/springboot/Application.java
package com.lzw.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author LiAng
*/
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
在下列目录放入图片

启动测试

注意事项和细节
- 静态资源访问原理:静态映射是 /**,也就是对所有请求拦截,请求进来,先看 Controller 能不能处理,不能处理的请求交给静态资源处理器,如果静态资源找不到则响应 404 页面。

改变静态资源访问前缀,比如我们希望
http://localhost:8080/lzwres/*
去请求静态资源应用场景:静态资源访问前缀和控制器请求路径冲突
创建 src/main/resources/application.yml
spring:
mvc:
static-path-pattern: /lzwres

- 改变默认的静态资源路径,比如希望在类路径下增加 lzwimg 目录 作为静态资源路径。

修改 application.yml
spring:
mvc:
static-path-pattern: /lzwres/**
web:
resources:
# 如果配置了 static-locations,原来的访问路径就被覆盖,如果需要保留,需要再指定一下
static-locations: ["classpath:/lzwimg/","classpath:/META-INF/resources/",
"classpath:/public/", "classpath:/static/","classpath:/resources/"] # 修改静态资源访问的路径
