springboot利用freemarker生成文档读取静态模板错误问题

           简述:springboot项目,html模板,最后生成pdf,我的模板放在resources目录下的

          一开始在freemarker配置中使用getClass().getClassLoader().getResource("htmlTemplate").getPath() 方式设置模板读取路径,如下:

    @Bean
    public Configuration getFreeMarkerConfiguration(){
        Configuration configuration = freeMarkerConfigurer.getConfiguration();

        try {
            configuration.setDirectoryForTemplateLoading(new File(getClass().getClassLoader().getResource("htmlTemplate").getPath()));
            configuration.setDefaultEncoding("UTF-8");
            configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);//.RETHROW
            configuration.setClassicCompatible(true);
        }
        catch (Exception e){

        }
        return configuration;
    }

在本地调试的时候成功将数据填充进模板并转成pdf,但是放到服务器上就会报错 ,提示获取不到模板。

freemarker.template.TemplateNotFoundException: Template not found for name "orderBill.html".

          原来 getClass().getClassLoader().getResource("htmlTemplate").getPath() 在本地调试的获取的是本地磁盘对应的绝对路径,但是项目打包发布到服务器后根据绝对路径获取静态文件肯定是不行的。

          经过研究发现模板的load方式不止一种,尝试使用classloader的方式来设置路径

代码修改如下:

 

    @Bean
    public Configuration getFreeMarkerConfiguration(){
        Configuration configuration = freeMarkerConfigurer.getConfiguration();

        try {
            configuration.setClassLoaderForTemplateLoading(getClass().getClassLoader(), "htmlTemplate");
//            configuration.setDirectoryForTemplateLoading(new File(getClass().getClassLoader().getResource("htmlTemplate").getPath()));
            configuration.setDefaultEncoding("UTF-8");
            configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);//.RETHROW
            configuration.setClassicCompatible(true);
        }
        catch (Exception e){

        }
        return configuration;
    }

这次在服务器上成功生成。

当然最简单的方法就是讲模板放到服务器的磁盘上,然后读取就方便了

代码之路道阻且长,特此记录

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值