如何在Thymeleaf中传递Java String[]数组作为翻译参数
问题场景
我尝试使用Thymeleaf的#{}语法,对Spring Boot控制器传递的字符串及参数进行翻译,当前写法如下:
<td th:text="#{__${notification.title}__(__${#strings.arrayToString(notification.titleArgs)}__)}"></td>
其中notification.title对应messages.properties中的消息键,notification.titleArgs是String类型数组,但运行时抛出模板解析异常:
org.thymeleaf.exceptions.TemplateProcessingException: Could not parse as expression: "#{${notification.title}(${#strings.arrayToString(notification.titleArgs)})}" (template: "user-notifications" - line 18, col 29)
at org.thymeleaf.standard.expression.StandardExpressionParser.parseExpression(StandardExpressionParser.java:131) ~[thymeleaf-3.1.1.RELEASE.jar:3.1.1.RELEASE]
at org.thymeleaf.standard.expression.StandardExpressionParser.parseExpression(StandardExpressionParser.java:62) ~[thymeleaf-3.1.1.RELEASE.jar:3.1.1.RELEASE]
...(省略后续栈追踪信息)
问题原因
- 错误使用
__${}__拼接表达式,导致Thymeleaf无法正确识别消息参数的数组类型——#strings.arrayToString()会把数组转为字符串,而消息解析需要的是原始数组参数,不是拼接后的字符串。 - 动态消息键的写法冗余,Thymeleaf支持直接在
#{}内部使用变量作为消息键,不需要额外转义。
正确解决方案
直接在#{}中传入动态消息键和原始数组参数即可:
<td th:text="#{${notification.title}(${notification.titleArgs})}"></td>
如果在迭代上下文(比如th:each循环)中,也可以用*{}简化变量引用:
<td th:text="#{${notification.title}(*{titleArgs})}"></td>
验证要点
确保messages.properties中对应的消息键定义了匹配数量的占位符,例如:
notification.order.alert=订单{0}状态更新为{1}
内容的提问来源于stack exchange,提问作者elianb

