SringBoot项目获取静态资源路径,FreeMark加载模板路径的几种方法总结——Jar包部署问题记录

本文介绍了在Java项目中使用FreeMarker模板引擎导出Word时遇到的问题及其解决方案。主要讨论了获取静态资源路径的方法,包括ClassPathResource和ResourceUtils,并对比了基于文件系统和类路径加载模板的不同。对于在jar包部署环境下无法加载模板的问题,提出了使用类路径加载和FreeMarkerConfigurer配置的推荐方法。总结中强调了在jar包部署中推荐的解决策略,并给出了方法一的替代思路,即通过输入流和临时文件处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、前言

在项目中使用FreeMark模板导出word的过程中,遇到一些问题,要不就是获取的模板路径不对,要不就是模板路径对,但是在jar包部署环境又不能成功加载模板。针对这几个问题做了下总结,以及解决的思路和过程。

二、获取静态资源路径:

方法一:

ClassPathResource classPathResource = new ClassPathResource("temp/word");
String path = classPathResource.getPath();

方法二:

String path = ResourceUtils.getURL("classpath:temp/word").getPath();

把这两个写在前面是为下面FreeMark加载模板路径做铺垫

三、FreeMark获取模板路径的几种方法:

方法一,基于文件系统加载模板:

Configuration configuration = new Configuration();
ClassPathResource classPathResource = new ClassPathResource("/temp/word"); 
File file = classPathResource.getFile(); configuration.setDirectoryForTemplateLoading(file);
Template template = configuration.getTemplate(tempname);

这种方式在编译环境没问题,在jar包上会报错,如下:

java.io.FileNotFoundException: class path resource [temp/word] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/D:/upload/test.jar!/BOOT-INF/classes!/temp/word。

可以看出,获取静态资源的路径是对的,为啥还会报错呢?

原因:打包之后,spring没办法通过File的形式访问jar包里面的文件。

这个种方式是不是就不能解决了呢?不是,也有解决方法,具体可以看后面的总结部分。

方法二,基于类路径加载模板(推荐):

Configuration configuration = new Configuration();
configuration.setClassForTemplateLoading(ExportDoc.class,"/temp/word");
Template template = configuration.getTemplate(tempname);

方法三,使用FreeMarkerConfigurer配置(推荐):

1.添加配置

freemarker:
  template-loader-path: classpath:/temp/word

2.引用FreeMarkerConfigurer配置

@Autowired
FreeMarkerConfigurer freeMarkerConfigurer;
Template template = freeMarkerConfigurer.getConfiguration().getTemplate(tempname);

总结:

如果是jar包部署方式,推荐方法二和方法三

方法一因为是文件的方式访问,所以不能加载jar里面的模板文件,那是不是就没有解决办法了呢?不是,方法一也有解决思路。

方法一解决的思路:

使用getInputStream()读取文件内容

缓存到临时文件,使用临时文件路径进行读取

示例代码:

ClassPathResource classPathResource = new ClassPathResource("/temp/word"+tempname);
InputStream inputStream = classPathResource.getInputStream();
File file = new File("D:/uplaod");
FileUtils.copyInputStreamToFile(inputStream,new File("D:/uplaod/"+tempname));
configuration.setDirectoryForTemplateLoading(file);
Template template = configuration.getTemplate(tempname);

但是因为这种方法,相对于其他两种比较麻烦,所以还是不推荐。

原创不易,转载请注明出处!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值