本文介绍了阅读在Freemarker模板引擎中导致TemplateException的Java对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写Java实用程序以使用freemarker模板生成输出文件.我有一个使用freemarker写入文件的对象列表.例如.我的java对象是具有fName,lName和age的雇员.我正在使用以下代码片段生成输出文件:

I am writing a Java Utility to generate output files using freemarker template. I have a List of objects that I write into a file using freemarker. E.g. My java object is an employee having fName, lName and age. I am using following code snippet to generate the output file:

<#list employees as e>
Fname: ${e.fName} Lname: ${e.lName} Age: ${e.age}
</#list>

现在,我正在使用一个自定义模板异常处理程序,该处理程序可在雇员对象中缺少fName,lName或age的情况下处理异常.

Now, I am using a custom template exception handler that handle exceptions in case fName, lName OR age is missing from the employee object.

configuration.setTemplateExceptionHandler(new FreemarkerExceptionHandler());

我想读取在FreemarkerExceptionHandler类中引发异常的雇员对象,但无法读取它.我正在使用以下代码读取员工列表,但正在获取所有员工,而不是导致此错误的一位特定员工.

I want to read the employee object that is throwing the exception in the FreemarkerExceptionHandler class, but am unable to read it. I am using the following code to read the list of employees, but am getting all the employees, rather than one specific employee that lead to this error.

TemplateHashModel templateHashModel = environment.getDataModel();

TemplateModel templateModel = templateHashModel.get("employees");
List<Employee> emps = simpleSequence.toList();

任何人都可以确认在freemarker中这是否可行以捕获导致异常的对象.

Can anyone please confirm if this is feasible in freemarker to catch the object that lead to exception.

推荐答案

据我所知,没有简单的方法可以做到这一点.我的想法是扩展DefaultObjectWrapper(假设您正在使用它-参见Configuration.getObjectWrapper),因此当通过TemplateHashModel.get(String)获取子变量(如fNameo)时,您可以在覆盖中捕获super.get(String)引发的任何异常的TemplateHashModel.get,然后抛出您自己的TemplateException子类实例,您将父对象放在该实例中,并为此添加了一个字段. (而且您可能还想将原始异常添加为异常的原因异常.)

There's no simple way to do that as far as I see. My idea is extending DefaultObjectWrapper (assuming you are using that - see Configuration.getObjectWrapper), so when the subvariable (like fNameo) is get via TemplateHashModel.get(String), you can catch any exceptions throw by super.get(String) in your override of TemplateHashModel.get, and then throw your own TemplateException subclass instance, into which you put the parent object in a field you have added for that. (And also you probably want to add the original exception as the cause exception of your exception.)

这篇关于阅读在Freemarker模板引擎中导致TemplateException的Java对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 21:01