Spring Boot 验证消息未得到解决

新手上路,请多包涵

我无法解析我的验证消息。

我已经在网上搜索和阅读几个小时了,我想将问题与 Customize spring validation error 的标记答案联系起来

我确实有一个 MessageSource bean 定义和 messages.properties 它被正确读取,因为我也用它来显示常规文本 th:text="#{some.prop.name} ,它确实工作得很好。只是验证错误不会按应有的方式工作。我确定这是我忽略的一个愚蠢的错误……验证本身工作正常。

约束:

 @NotEmpty(message="{validation.mail.notEmpty}")
@Email()
private String mail;

消息.属性:

 # Validation
validation.mail.notEmpty=The mail must not be empty!

模板部分:

 <span th:if="${#fields.hasErrors('mail')}" th:errors="*{mail}"></span>

显示的文字:

 {validation.mail.notEmpty}

我尝试了很多变体,但都没有成功。

 @NotEmpty(message="validation.mail.notEmpty")
@NotEmpty(message="#{validation.mail.notEmpty}")

将只显示消息字符串的确切值,不进行解析。

 <span th:if="${#fields.hasErrors('mail')}" th:errors="${mail}"></span>
<span th:if="${#fields.hasErrors('mail')}" th:errors="#{mail}"></span>
<span th:if="${#fields.hasErrors('mail')}" th:errors="#{*{mail}}"></span>
<span th:if="${#fields.hasErrors('mail')}" th:errors="#{__*{mail}__}"></span>

会导致错误。


编辑:

调试后,我偶然发现了这个:

班级: org.springframework.context.support.MessageSourceSupport

方法: formatMessage(String msg, Object[] args, Locale locale)

将被称为

formatMessage("{validation.mail.notEmpty}", null, locale /*German Locale*/)

它会遇到 if (messageFormat == INVALID_MESSAGE_FORMAT) {

所以…我的消息格式不正确。这超出了我的范围/知识范围。任何人都知道这是什么意思?

原文由 Korashen 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 474
2 个回答

看起来您在应用程序配置中缺少 LocalValidatorFactoryBean 定义。 Below you can find an example of Application class that defines two beans: LocalValidatorFactoryBean and MessageSource that uses messages.properties file.

 import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

@SpringBootApplication
public class Application {

    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:messages");
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }

    @Bean
    public LocalValidatorFactoryBean validator() {
        LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
        bean.setValidationMessageSource(messageSource());
        return bean;
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

定义了 LocalValidatorFactoryBean bean,您可以使用自定义验证消息,例如:

 @NotEmpty(message = "{validation.mail.notEmpty}")
@Email
private String email;

messages.properties

 validation.mail.notEmpty=E-mail cannot be empty!

和 Thymeleaf 模板文件:

 <p th:if="${#fields.hasErrors('email')}" th:errors="*{email}">Name Error</p>

示例应用程序

https://github.com/wololock/stackoverflow-answers/tree/master/45692179

我已经准备好反映您的问题的示例 Spring Boot 应用程序。随意克隆它并在本地运行它。如果随表单发布的值不符合 @NotEmpty@Email 验证,它将显示翻译后的验证消息。

WebMvcConfigurerAdapter 配置

在扩展 WebMvcConfigurerAdapter 的情况下,您必须通过覆盖父类的 getValidator() 方法来提供验证程序,例如:

 import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@EnableWebMvc
public class WebConfiguration extends WebMvcConfigurerAdapter {

    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:messages");
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }

    @Bean
    @Override
    public Validator getValidator() {
        LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
        bean.setValidationMessageSource(messageSource());
        return bean;
    }

    // other methods...
}

否则,如果您在其他地方定义 LocalValidatorFactoryBean bean,它将被覆盖并且不会有任何效果。

我希望它有所帮助。

原文由 Szymon Stepniak 发布,翻译遵循 CC BY-SA 3.0 许可协议

不确定您使用的是哪个版本的 spring boot。我正在使用 Spring 引导 2.0.1.RELEASE 。更清晰的解决方案是将所有验证消息移至 ValidationMessages.properties 。这样您就不必覆盖自动配置的 Validator() 和设置 MessageSource

原文由 want2learn 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题