13. 处理静态资源(自定义资源映射)【从零开始学Spring Boot】

 

【视频 & 交流平台】

à SpringBoot视频

http://study.163.com/course/introduction.htm?courseId=1004329008&utm_campaign=commission&utm_source=400000000155061&utm_medium=share

à SpringCloud视频

http://study.163.com/course/introduction.htm?courseId=1004638001&utm_campaign=commission&utm_source=400000000155061&utm_medium=share

à Spring Boot源码

https://gitee.com/happyangellxq520/spring-boot

à Spring Boot交流平台

http://412887952-qq-com.iteye.com/blog/2321532

 

 

上面我们介绍了Spring Boot 的默认资源映射,一般够用了,那我们如何自定义目录? 
这些资源都是打包在jar包中的,然后实际应用中,我们还有很多资源是在管理系统中动态维护的,并不可能在程序包中,对于这种随意指定目录的资源,如何访问?

自定义目录

以增加 /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;

 

@Configuration

public class MyWebAppConfigurer

        extends WebMvcConfigurerAdapter {

 

    @Override

    public 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");

 

【视频&交流平台】

à Spring Boot视频

http://study.163.com/course/introduction.htm?courseId=1004329008

à Spring Cloud视频

http://study.163.com/course/introduction.htm?courseId=1004638001

à Spring Boot源码

https://gitee.com/happyangellxq520/spring-boot

à Spring Boot交流平台

http://412887952-qq-com.iteye.com/blog/2321532

  

 

网易云课堂视频最新更新

第十一章 Spring Boot 日志

1、spring boot日志—理论

2、Spring Boot日志-logback

3、Spring Boot日志-log4j2

第十二章 Spring Boot 知识点2

1、spring boot 服务配置和部署

2、Spring Boot 定制URL匹配规则

 

 

猜你喜欢

转载自412887952-qq-com.iteye.com/blog/2292098