首页 > 解决方案 > 使用 thymeleaf 将上下文绑定到 html 模板时出错

问题描述

我正在尝试将一些表单数据转换为 html 模板,并最终使用 iText 转换为 PDF。在线上:

String processedHtml = templateEngine.process(templateName, ctx);

我得到错误:

2018-09-12 12:13:17.680 错误 18264 --- [nio-8080-exec-3] org.thymeleaf.TemplateEngine:[THYMELEAF][http-nio-8080-exec-3] 异常处理模板“输出。 html”:模板解析时出错(模板:“类路径资源[templates/output.html]”)

原因:org.attoparser.ParseException:无法处理属性“{th:field,data-th-field}”:没有为预期的表单绑定操作找到关联的 BindStatus。这可能是由于缺少对 Spring RequestContext 的适当管理,这通常通过 org.attoparser.MarkupParser.parseDocument(MarkupParser .java:393) ~[attoparser-2.0.4.RELEASE.jar:2.0.4.RELEASE] at org.attoparser.MarkupParser.parse(MarkupParser.java:257) ~[attoparser-2.0.4.RELEASE.jar: 2.0.4.RELEASE] at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:230) ~[thymeleaf-3.0.9.RELEASE.jar:3.0.9.RELEASE] ...省略了 61 个常见框架

output.html 第 52 行是:

   <input type="number" class="form-control inputnid person text-uppercase" 
         data-property="nid" id="nid" placeholder="NID" 
         th:field="*{assessment.nid}"/>

完整的方法是:

public class PdfGeneratorUtil { 

    public static final String BASEURI = "src/main/resources/static"; 
    @Qualifier("templateEngine") 
    @Autowired 
    private TemplateEngine templateEngine; 

    public void createPdf(String templateName, Map map) throws Exception { 
        Assert.notNull(templateName, "The templateName can not be null"); 
        Context ctx = new Context(); 
        if (map != null) { 
            Iterator itMap = map.entrySet().iterator(); 
            while (itMap.hasNext()) { 
                Map.Entry pair = (Map.Entry) itMap.next(); 
                ctx.setVariable(pair.getKey().toString(), pair.getValue()); 
            } 
        } 

        String processedHtml = templateEngine.process(templateName, ctx); 
        PdfWriter writer = new PdfWriter("C:\\tmp\\assessment.pdf"); 
        PdfDocument pdfDoc = new PdfDocument(writer); 
        ConverterProperties converterProperties = new ConverterProperties().setBaseUri(BASEURI); 
        HtmlConverter.convertToPdf(processedHtml, pdfDoc, converterProperties); 
        System.out.println("PDF created successfully"); 
    } 
}

标签: javahtmlspring-bootitextthymeleaf

解决方案


找到了修复。正如 th:field 提示的堆栈跟踪应该 th:checked 复选框。


推荐阅读