项目场景:
近期在项目开发中,遇到了一个由Thymeleaf模板解析引起的异常,具体的异常信息如下:
org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: “class path resource Caused by: org.thymeleaf.exceptions.
org.thymeleaf.exceptions.TemplateProcessingException: Could not parse as expression: "
{type: ‘checkbox’, fixed: ‘left’} ,
{field: ‘id’, title: ‘序号’, width: 120, fixed: ‘left’, unresize: true, sortName: true} ,
{field: ‘name’, title: ‘种类名称’, width: 400, edit: ‘text’} ,
{fixed: ‘right’, title: ‘操作’, toolbar: ‘#barDemo’, width: 250} "
(template: “admin/types” - line 314, col 27)
问题描述
异常发生在Thymeleaf模板解析阶段,具体的错误位置在 "page/xxx" 模板的第43行第26列。异常的主要原因是在以下字符串片段:
{type: ‘checkbox’, fixed: ‘left’} ,
{field: ‘id’, title: ‘序号’, width: 120, fixed: ‘left’, unresize: true, sortName: true} ,
{field: ‘name’, title: ‘种类名称’, width: 400, edit: ‘text’} ,
{fixed: ‘right’, title: ‘操作’, toolbar: ‘#barDemo’, width: 250}
原因分析:
在 “admin/types” 页面,以下字符串片段:
{type: ‘checkbox’, fixed: ‘left’} ,
{field: ‘id’, title: ‘序号’, width: 120, fixed: ‘left’, unresize: true, sortName: true} ,
{field: ‘name’, title: ‘种类名称’, width: 400, edit: ‘text’} ,
{fixed: ‘right’, title: ‘操作’, toolbar: ‘#barDemo’, width: 250}
实际上是layui表格列的格式描述,但Thymeleaf解析时将其误认为是表达式,导致异常的发生。Thymeleaf对模板进行解析时期望找到合法的表达式,但在这里却遇到了不符合表达式语法的内容。
解决方案:
为了解决这个异常,需要将该字符串两边多余的中括号进行调整。将以下形式:
[[
{type: ‘checkbox’, fixed: ‘left’} ,
{field: ‘id’, title: ‘序号’, width: 120, fixed: ‘left’, unresize: true, sortName: true} ,
{field: ‘name’, title: ‘种类名称’, width: 400, edit: ‘text’} ,
{fixed: ‘right’, title: ‘操作’, toolbar: ‘#barDemo’, width: 250}
]]
改为以下形式:
[
[
{type: ‘checkbox’, fixed: ‘left’} ,
{field: ‘id’, title: ‘序号’, width: 120, fixed: ‘left’, unresize: true, sortName: true} ,
{field: ‘name’, title: ‘种类名称’, width: 400, edit: ‘text’} ,
{fixed: ‘right’, title: ‘操作’, toolbar: ‘#barDemo’, width: 250}
]
]
即在两对中括号中间加空格或者换行都行
总结
在使用Thymeleaf模板引擎时,特别需要注意模板中可能存在的与表达式语法相似但实际上不是表达式的内容。在本次异常中,对layui表格列格式的误解导致了Thymeleaf的异常解析。通过调整模板中的中括号,成功解决了这一异常问题。希望本文对类似问题的解决提供了参考,以减少在项目开发中的不必要困扰。