100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > Spring Boot处理静态资源(自定义资源映射)

Spring Boot处理静态资源(自定义资源映射)

时间:2023-02-26 14:45:02

相关推荐

Spring Boot处理静态资源(自定义资源映射)

独角兽企业重金招聘Python工程师标准>>>

Spring Boot默认是使用resources下的静态资源进行映射。如果我们需要增加以/myres/*映射到classpath:/myres/*为例的代码处理为:

实现类继承WebMvcConfigurerAdapter并重写方法addResourceHandlers

package org.springboot.sample.config;import org.springboot.sample.interceptor.MyInterceptor1;import org.springboot.sample.interceptor.MyInterceptor2;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;@Configurationpublic class MyWebAppConfigurerextends WebMvcConfigurerAdapter {@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/myres/**").addResourceLocations("classpath:/myres/");super.addResourceHandlers(registry);}}

访问myres文件夹中的test.jpg图片的地址为http://localhost:8080/myres/test.jpg

这样使用代码的方式自定义目录映射,并不影响Spring Boot的默认映射,可以同时使用。

如果我们将/myres/*修改为/*与默认的相同时,则会覆盖系统的配置,可以多次使用addResourceLocations添加目录,优先级先添加的高于后添加的。

其中addResourceLocations的参数是动参,可以这样写addResourceLocations(“classpath:/img1/”, “classpath:/img2/”, “classpath:/img3/”);

如果我们要指定一个绝对路径的文件夹(如D:/data/api_files),则只需要使用addResourceLocations指定即可。

//可以直接使用addResourceLocations指定磁盘绝对路径,同样可以配置多个位置,注意路径写法需要加上file:

registry.addResourceHandler("/api_files/**").addResourceLocations("file:D:/data/api_files");

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。