当前位置: 移动技术网 > IT编程>开发语言>Java > springboot操作静态资源文件的方法

springboot操作静态资源文件的方法

2019年07月19日  | 移动技术网IT编程  | 我要评论

默认静态资源供

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
      

在中该如何引用上面的静态资源呢?

 如下写法:

<link rel="stylesheet" type="text/css" href="/css/index.css" rel="external nofollow" >
<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包中了,于是通过以上配置可以就可通过直接访问在/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

还是推荐第一种写法把。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网