有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

未解析java Spring启动验证消息

我在解决验证消息时遇到问题

我一直在网上搜索和阅读,所以几个小时以来,我想把这个问题与Customize spring validation error的标记答案联系起来

我确实定义了一个MessageSourcebean和消息。属性可以正确读取,因为我还使用它来显示带有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) {

所以。。。我的邮件格式不正确。这超出了我的范围/知识范围。有人知道那是什么意思吗


共 (6) 个答案

  1. # 1 楼答案

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

  2. # 2 楼答案

    您好,先生,

    关于“Wais Shuja”和“Ramesh Singh”的答案,我对此表示确认,因为我认为这是您寻求的正确解决方案。我扩展他们的答案:

    在文件夹/resources/中,您可以创建支持的语言所需的文件。在我的网络应用程序中,我使用德语和英语。因此,我创建了以下两个文件:

     - ValidationMessages_en.properties
     - ValidationMessages_de.properties
    

    然后,感谢Spring magic,您可以这样做:

    @NotNull(message = "{error.mandatory}")
    @Size(min = 1, message = "{error.mandatory}")
    private String forname;
    

    根据CookieLocaleResolver中存储的语言,Spring选择适当的文件并插入文本

    亲切问候
    奥顿汽车旅馆

  3. # 3 楼答案

    我也有同样的问题,在阅读了这里的答案后,我发现文件名应该是”ValidationMessages。属性“。 我先给它取了个别的名字,它对我也不起作用。直到我将其重命名为ValidationMessages。属性

  4. # 4 楼答案

    对于rest控制器,您必须在方法参数的请求主体上添加@Valid注释。e、 g

    @PostMapping
    public User create(@Valid @RequestBody User user){
      //...
    }
    
  5. # 5 楼答案

    应用程序配置中似乎缺少LocalValidatorFactoryBean定义。下面是Application类的一个示例,它定义了两个bean:LocalValidatorFactoryBean和使用messages.properties文件的MessageSource

    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);
        }
    }
    

    定义了LocalValidatorFactoryBeanbean后,您可以使用如下自定义验证消息:

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

    消息。属性

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

    和包含以下内容的模板文件:

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

    示例应用程序

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

    我已经准备了反映您的问题的示例Spring引导应用程序。您可以随意克隆它并在本地运行它。如果表单中发布的值不符合@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...
    }
    

    否则,如果在其他位置定义LocalValidatorFactoryBeanbean,它将被覆盖,并且不会产生任何效果

    我希望有帮助

  6. # 6 楼答案

    我使用的是SpringBoot的2.2.7版本,它的工作原理是将属性文件名更改为ValidationMessages。属性,不需要其他配置