Spring Boot验证消息未解析 [英] Spring Boot validation message is not being resolved

查看:154
本文介绍了Spring Boot验证消息未解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法让我的验证消息得到解决。

I am having trouble getting my validation message to be resolved.

我一直在网上搜索和阅读SO几个小时了,我想要关联有关自定义弹簧验证错误的明确答案的问题

I have been searching and reading through the web and SO for some hours now, I want to relate the question with the marked answer of Customize spring validation error

我确实已经定义了 MessageSource bean,并且正确读取了 messages.properties ,因为我也将它用于常规用 th:text =#{some.prop.name} 显示的文本,它确实可以正常工作。
这只是赢得的验证错误我应该按照应该的方式工作。
我确定这是一个我忽略的愚蠢错误...
验证本身工作正常。

I do have a MessageSource bean defined and the messages.properties it getting read correctly, as I also use it for regular text to be displayed with th:text="#{some.prop.name}, which does work absolutely fine. It is just the validation error that won't work the way it should. I'm sure it's a stupid mistake I just overlook... The validation itself works fine.

约束:

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

messages.properties:

messages.properties:

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

模板部分:

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

显示的文字:

{validation.mail.notEmpty}

我尝试了很多变化,一切都没有成功。

I tried a lot of variation, all without success.

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

只显示消息字符串的确切值,没有解析。

Will just show the exact value of the messages string, no parsing.

<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){

所以...我的留言格式不正确。这超出了我的范围/知识。任何人都知道这意味着什么?

So... my message format is not correct. This is way out of my scope/knowledge. Anyone knows what that means?

推荐答案

看起来你错过了 LocalValidatorFactoryBean 在应用程序配置中定义。您可以在下面找到定义两个bean的 Application 类的示例: LocalValidatorFactoryBean MessageSource 使用 messages.properties 文件。

It looks like you are missing LocalValidatorFactoryBean definition in your application configuration. 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定义你可以使用自定义验证消息,如:

Having LocalValidatorFactoryBean bean defined you can use custom validation message like:

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

messages.properties

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

和Thymeleaf模板文件包含:

and Thymeleaf template file with:

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



样本申请



Sample application


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

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

I have prepared sample Spring Boot application that reflects your problem. Feel free to clone it and run it locally. It will display translated validation message if value posted with form does not meet @NotEmpty and @Email validation.

如果延长 WebMvcConfigurerAdapter 您必须通过从父类重写 getValidator()方法来提供验证器,例如:

In case of extending WebMvcConfigurerAdapter you will have to provide validator by overriding getValidator() method from parent class, e.g.:

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,它将被覆盖并且不会产生任何影响。

Otherwise if you define LocalValidatorFactoryBean bean in other place it will get overridden and there will be no effect.

我希望它有所帮助。

这篇关于Spring Boot验证消息未解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆