详细内容见官方文档:Static Content
创建一个SpringBoot的WebDemo,创建WebDemo具体步骤—>【如何创建一个SpringBoot的WebDemo】笔记方法二使用Spring Initializr创建一个Spring Boot项目
按照上述链接笔记中的步骤创建好WebDemo后测试正常运行后再进行下面的步骤,
此时项目的默认端口号应该为8080
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.
默认情况下,Spring Boot从类路径中名为/static(或/public或/resources或/META-INF/resources)的目录或ServletContext的根目录提供静态内容。 它使用Spring MVC中的ResourceHttpRequestHandler,因此您可以通过添加自己的WebMvcConfigurer并覆盖addResourceHandlers方法来修改该行为。
任意的选几个图片复制粘贴到目录中
测试结果:在第二步中我们添加的四个图片均能访问
总结:
package org.example.webdemo.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @GetMapping("/1.jpg") public String hello(){ return "hello cxk"; } }
此时我们再来访问127.0.0.1:8080/1.jpg,发现不再显示图片,服务端响应的是我们自定义字符串。
By default, resources are mapped on /**
, but you can tune that with the spring.mvc.static-path-pattern property. For instance, relocating all resources to /resources/**
can be achieved as follows:
默认情况下,资源映射在/**
上,但您可以使用spring.mvc.static-path-pattern属性进行调整。 例如,将所有资源转移到/resources/**
可以通过以下方式实现:
在application.yaml中做如下配置
spring: mvc: static-path-pattern: "/res/**"
此时再去访问127.0.0.1:8080/2.jpg,发现报404了
访问127.0.0.1:8080/res/2.jpg,发现必须在我们配置res前缀下才能访问静态资源
You can also customize the static resource locations by using the spring.web.resources.static-locations property (replacing the default values with a list of directory locations). The root servlet context path, “/”, is automatically added as a location as well.
您还可以使用spring.web.resources.static-locations属性(将默认值替换为目录位置列表)自定义静态资源位置。 根servlet上下文路径"/"也会自动添加为位置。
server: port: 8080 spring: mvc: static-path-pattern: "/res/**" web: resources: static-locations: classpath:/hello12345/
server: port: 8080 spring: mvc: static-path-pattern: "/res/**" web: resources: static-locations: [classpath:/hello12345/,classpath:/nihao123/]
http://127.0.0.1:8080/res/nihao.jpg