You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Thymeleaf中使用西里尔文关键字?问题排查与解决

Thymeleaf中使用西里尔文变量关键字的问题与解决方法

问题场景

用户尝试在Thymeleaf中使用西里尔文作为变量关键字时触发模板解析异常,相关配置与代码如下:

配置类

@Bean
public SpringTemplateEngine springTemplateEngine() {
    SpringTemplateEngine templateEngine = new SpringTemplateEngine();
    StringTemplateResolver stringTemplateResolver = new StringTemplateResolver();
    templateEngine.addTemplateResolver(stringTemplateResolver);
    return templateEngine;
}

业务类

public class TemplateConverter {

private SpringTemplateEngine templateEngine;

private final static String TEMPLATE_LOCAL = "RU";

public String getTemplateFromAttributes(String template, Map<String, Object> attr) {
    Context context = new Context(new Locale(TEMPLATE_LOCAL));
    if (!CollectionUtils.isEmpty(attr)) {
        attr.forEach((k, v) -> context.setVariable(k, v));
    }

    return templateEngine.process(template, context);
    }
}

成功示例(英文关键字)

//..
String template = "Привет [(${keyword})]";
String result = templateConverter.getTemplateFromAttributes(template, Map.of("keyword", "мир"));
System.out.println(result); // "Привет мир"

失败示例(西里尔文关键字)

//..
String template = "Привет [(${ключевое_слово})]";
String result = templateConverter.getTemplateFromAttributes(template, Map.of("ключевое_слово", "мир"));  // 抛出异常
System.out.println(result);

错误日志

00:47:07.123 [main] DEBUG org.thymeleaf.TemplateEngine - [THYMELEAF] TEMPLATE ENGINE INITIALIZED
00:47:07.196 [main] ERROR org.thymeleaf.TemplateEngine - [THYMELEAF][main] Exception processing template "Привет [(${ключевое_слово})]": An error happened during template parsing (template: "Привет [(${ключевое_слово})]")
org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "Привет [(${ключевое_слово})]")
    at org.thymeleaf.templateparser.text.AbstractTextTemplateParser.parse(AbstractTextTemplateParser.java:180)
    ...

排查说明

设置TEMPLATE_LOCAL = "RU"无法解决问题,StringTemplateResolver无UTF-8关键字相关配置项。

解决方案

  • 更换Maven依赖:
    原依赖:
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
   <version>2.7.5</version>
</dependency>

替换为:

<dependency>
  <groupId>org.thymeleaf</groupId>
  <artifactId>thymeleaf</artifactId>
  <version>3.1.1.RELEASE</version>
</dependency>
  • 修改引擎类型,将SpringTemplateEngine替换为TemplateEngine:
@Bean
public TemplateEngine springTemplateEngine() {
    TemplateEngine templateEngine = new TemplateEngine();
    StringTemplateResolver stringTemplateResolver = new StringTemplateResolver();
    templateEngine.addTemplateResolver(stringTemplateResolver);
    return templateEngine;
}

内容的提问来源于stack exchange,提问作者Илья Косолапов

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 11:46:06