【问题标题】:SpringBoot: accessing custom i18n validation message programmaticallySpringBoot:以编程方式访问自定义 i18n 验证消息
【发布时间】:2020-08-06 13:36:06
【问题描述】:

这里有一个简单的问题:我正在开发一个具有 3 个语言版本的 Spring Boot 网站,我使用 messages_xx.properties 将消息国际化,其中 xx 是语言前缀,以及以下代码:

    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver slr = new SessionLocaleResolver();
        slr.setDefaultLocale(Locale.US);
        return slr;
    }

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
        lci.setParamName("lang");
        return lci;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeChangeInterceptor());
    }

这很好用。然后,为了简单起见,我还创建了 ValidationMessages_xx.properties 进行验证,它也可以正常工作。当我需要以编程方式从 ValidationMessages 访问某些消息时,就会出现问题,例如:

        if (!userDto.getPassword().equals(userDto.getRepeatPassword())) {
            bindingResult.rejectValue("repeatPassword", "error.repeatPassword", "custom.validation.passwordsDontMatch.message");
        }

问题在于rejectValue 的第三个参数——我需要在这里以某种方式替换来自ValidationMessages 的消息。但是上面显示的代码只返回文字字符串“custom.validation.passwordsDontMatch.message”,即使当我将光标放在字符串上时,Idea 编辑器在此处显示它“看到”来自 ValidationMessages 的正确消息。这也不起作用:

bindingResult.rejectValue("username", "error.username", "${custom.validation.passwordsDontMatch.message}");

如何从 Java 类访问 custom.validation.passwordsDontMatch.message 字符串?

【问题讨论】:

    标签: java spring spring-boot validation internationalization


    【解决方案1】:
    ResourceBundle bundle = ResourceBundle.getBundle("ValidationMessages", LocaleContextHolder.getLocale());
    String value = bundle.getString("custom.validation.passwordsDontMatch.message");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-12
      • 2014-05-31
      • 2011-10-21
      • 2014-08-15
      • 1970-01-01
      • 2017-06-28
      相关资源
      最近更新 更多