springboot操作静态资源文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zombres/article/details/80896059

默认静态资源供

SpringBoot有几个默认的静态资源目录,当然也可配置,默认配置的/**映射到/static(或/public ,/resources,/META-INF/resources),自定义配置方式如下:

spring.mvc.static-path-pattern=/** # Path pattern used for static resources.

前端如果需要访问默认的静态资源,下面有点要注意,考虑下面的目录结构:

└─resources
    │  application.yml
    │
    ├─static
    │  ├─css
    │  │      index.css
    │  │
    │  └─js
    │          index.js
    │
    └─templates
            index.html

在index.html中该如何引用上面的静态资源呢?
如下写法:

<link rel="stylesheet" type="text/css" href="/css/index.css">
<script type="text/javascript" src="/js/index.js"></script>

注意:默认配置的/**映射到/static(或/public ,/resources,/META-INF/resources)
当请求/css/index.css的时候,Spring MVC 会在/static/目录下面找到。
如果配置为/static/css/index.css,那么上面配置的几个目录下面都没有/static目录,因此会找不到资源文件!
所以写静态资源位置的时候,不要带上映射的目录名(如/static/,/public/ ,/resources/,/META-INF/resources/)!

自定义静态资源

网上资料说可以在配置文件中定义指定,我没有用这种方式,我使用的是通过实现扩展Configuration来实现。
PS:说明一下在SpringBoot 1.x的版本中,都是通过继承WebMvcAutoConfiguration来扩展一些与Spring MVC相关的配置,但在2.x的版本中,直接实现接口WebMvcConfigurer来扩展Spring MVC的相关功能,如配置拦截器,配置通用返回值处理器,配置统一异常处理等,当然还包括配置本文中的自定义静态资源路径,覆盖里面等default方法即可。
直接上代码吧:

@Configuration
public class MyWebAppConfigurer implements WebMvcConfigurer {

    // event.share.image.dir=/data/share/image/
    @Value("${event.share.image.dir}")
    private String outputDir;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/share/image/**").addResourceLocations(
                "file:"+outputDir);
    }
}

说明:上面代码的背景是从别的地方动态拿过来的图片,肯定不能在放到SringBoot的jar包中了,于是通过以上配置可以就可通过http://host/share/image/a.jpg直接访问在/data/share/image/a.jpg图片了。如果静态资源文件不是动态的,也在resources目录下面,只是需要下面这样写即可:

registry.addResourceHandler("/share/image/**").addResourceLocations(
                "classpath:"+outputDir);  // 把file换成classpath

通过SpringBoot工具类访问静态资源

很简单,代码如下:

private static final String BACKGROUND_IMAGE = "share/background.jpg";

File file = new ClassPathResource(BACKGROUND_IMAGE).getFile();
InputStream is = new ClassPathResource(BACKGROUND_IMAGE).getInputStream(); 

原来还有一种写法:

private static final String BACKGROUND_IMAGE = "classpath:share/background.jpg";
File file = ResourceUtils.getFile(BACKGROUND_IMAGE);

但在2.x版本中,可能出现下面但异常

java.io.FileNotFoundException: class path resource [share/background.jpg] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/home/ubuntu/wxcs/calendar-api-1.0.0.jar!/BOOT-INF/classes!/share/background.jpg

还是推荐第一种写法把。

猜你喜欢

转载自blog.csdn.net/zombres/article/details/80896059