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

Spring Boot+STS+Thymeleaf多语言场景下表单校验消息无法正常翻译问题

问题根因

Hibernate Validator 默认使用自带的独立消息资源池,没有关联你项目中配置的自定义多语言资源文件,导致校验注解里的占位符无法读取到对应语言的翻译值。

解决步骤

  • 第一步:确认资源配置正确
    首先校验所有语言的properties资源文件中都存在city.notblank对应的翻译配置,示例如下:
    # messages_zh_CN.properties
    city.notblank=城市不能为空
    
    # messages_en_US.properties
    city.notblank=City cannot be empty
    
    同时确认application配置文件中已正确指定资源文件路径:
    # application.yml
    spring:
      messages:
        basename: messages # 若资源文件放在i18n目录下则写为i18n/messages
        encoding: UTF-8
    
  • 第二步:自定义校验器绑定自定义消息源
    新增校验配置类,将项目的多语言消息源注入到校验器中,替换默认的校验消息源:
    import org.springframework.context.MessageSource;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
    
    @Configuration
    public class ValidationConfig {
    
        private final MessageSource messageSource;
    
        public ValidationConfig(MessageSource messageSource) {
            this.messageSource = messageSource;
        }
    
        @Bean
        public LocalValidatorFactoryBean validator() {
            LocalValidatorFactoryBean validatorFactory = new LocalValidatorFactoryBean();
            validatorFactory.setValidationMessageSource(messageSource);
            return validatorFactory;
        }
    }
    
  • 第三步:确认页面校验语法正确
    Thymeleaf页面渲染校验消息时使用官方推荐的绑定语法,不要手动硬编码消息获取逻辑:
    <span th:if="${#fields.hasErrors('city')}" th:errors="*{city}" class="error-tip"></span>
    

配置完成后重启项目,切换语言后再触发表单校验即可看到对应语言的提示消息。

内容的提问来源于stack exchange,提问作者developer_user

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 02:15:03