一、前言
在项目中使用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);
但是因为这种方法,相对于其他两种比较麻烦,所以还是不推荐。
原创不易,转载请注明出处!