Thymeleaf引入messages.properties至JSON-LD脚本时加载失败报错
解决Thymeleaf中在application/ld+json里引入messages.properties内容的问题
错误根源分析
- 表达式误用:混淆了Thymeleaf两种核心表达式——
${}用于读取Model中的后端传递变量,而读取messages.properties这类国际化消息文件,必须用消息表达式#{}。错误日志里的faq为null,正是因为你用${faq.question1}试图读取不存在的Model变量,而非messages中的配置项。 - 语法嵌套违规:将
<th:block>直接嵌套在JSON字符串值中,不符合Thymeleaf的模板解析规则,导致模板处理失败。
正确实现方式
方式1:使用Thymeleaf内联模式(推荐)
通过th:inline="javascript"开启内联支持(JSON属于JavaScript子集,可直接适配),用[[...]]包裹消息表达式,Thymeleaf会自动转义特殊字符、保证JSON结构合法:
<script type="application/ld+json" th:inline="javascript"> { "@context": "https://schema.org", "@type": "FAQPage", "mainEntity": [{ "@type": "Question", "name": [[#{faq.question1}]], "acceptedAnswer": { "@type": "Answer", "text": [[#{faq.answer1}]] } }] } </script>
方式2:通过th:text构建完整JSON
如果不想使用内联,可直接用<th:block>的th:text属性生成整个JSON内容:
<script type="application/ld+json"> <th:block th:text='{"@context": "https://schema.org", "@type": "FAQPage", "mainEntity": [{"@type": "Question", "name": "#{faq.question1}", "acceptedAnswer": {"@type": "Answer", "text": "#{faq.answer1}"}]}'></th:block> </script>
额外注意事项
- 确保
messages.properties文件放置在Spring Boot项目的src/main/resources目录下,Spring框架会自动加载该文件。 - 若涉及多语言国际化,需按规范命名消息文件(如
messages_en.properties、messages_zh.properties),并配置正确的国际化解析器。
内容的提问来源于stack exchange,提问作者Nunyet Calçada
相关产品推荐
相关产品推荐

