Java Spring Boot 验证消息未得到解决
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45692179/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring Boot validation message is not being resolved
提问by Korashen
I am having trouble getting my validation message to be resolved.
我无法解决我的验证消息。
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
我已经在网上搜索和阅读了几个小时,我想将问题与自定义弹簧验证错误的标记答案联系起来
I do have a MessageSource
bean defined and the messages.propertiesit 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.
我确实MessageSource
定义了一个bean,并且可以正确读取它的messages.properties,因为我还使用它来显示与 一起显示的常规文本th:text="#{some.prop.name}
,它确实可以正常工作。只是验证错误无法正常工作。我确定这是一个我忽略的愚蠢错误......验证本身工作正常。
Constraint:
约束:
@NotEmpty(message="{validation.mail.notEmpty}")
@Email()
private String mail;
messages.properties:
消息。属性:
# Validation
validation.mail.notEmpty=The mail must not be empty!
Template part:
模板部分:
<span th:if="${#fields.hasErrors('mail')}" th:errors="*{mail}"></span>
The displayed text:
显示的文字:
{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>
Will result in an error.
会导致错误。
EDIT:
编辑:
After debugging, I stumbled up on this:
调试后,我偶然发现了这一点:
Class: org.springframework.context.support.MessageSourceSupport
班级: org.springframework.context.support.MessageSourceSupport
Method: formatMessage(String msg, Object[] args, Locale locale)
方法: formatMessage(String msg, Object[] args, Locale locale)
will be called with
将被调用
formatMessage("{validation.mail.notEmpty}", null, locale /*German Locale*/)
formatMessage("{validation.mail.notEmpty}", null, locale /*German Locale*/)
And it will run into if (messageFormat == INVALID_MESSAGE_FORMAT) {
它会遇到 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?
所以...我的消息格式不正确。这超出了我的范围/知识。有谁知道那是什么意思?
采纳答案by Szymon Stepniak
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.
看起来LocalValidatorFactoryBean
您的应用程序配置中缺少定义。您可以在下面找到Application
定义两个 bean的类示例:LocalValidatorFactoryBean
并MessageSource
使用messages.properties
文件。
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);
}
}
Having LocalValidatorFactoryBean
bean defined you can use custom validation message like:
有LocalValidatorFactoryBean
豆定义您可以使用自定义的验证信息,如:
@NotEmpty(message = "{validation.mail.notEmpty}")
@Email
private String email;
and messages.properties:
和messages.properties:
validation.mail.notEmpty=E-mail cannot be empty!
and Thymeleaf template file with:
和 Thymeleaf 模板文件:
<p th:if="${#fields.hasErrors('email')}" th:errors="*{email}">Name Error</p>
Sample application
示例应用程序
https://github.com/wololock/stackoverflow-answers/tree/master/45692179
https://github.com/wololock/stackoverflow-answers/tree/master/45692179
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.
我准备了反映您的问题的示例 Spring Boot 应用程序。随意克隆它并在本地运行它。如果与表单一起发布的值不符合@NotEmpty
和@Email
验证,它将显示翻译的验证消息。
WebMvcConfigurerAdapter
configuration
WebMvcConfigurerAdapter
配置
In case of extending WebMvcConfigurerAdapter
you will have to provide validator by overriding getValidator()
method from parent class, e.g.:
在扩展的情况下,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...
}
Otherwise if you define LocalValidatorFactoryBean
bean in other place it will get overridden and there will be no effect.
否则,如果您LocalValidatorFactoryBean
在其他地方定义bean,它将被覆盖并且没有任何效果。
I hope it helps.
我希望它有帮助。
回答by want2learn
Not sure which version of spring boot you are using. I am using Spring boot 2.0.1.RELEASE
. A clearer solution would be move all your validation messages to ValidationMessages.properties
. This way you don't have to override the auto-configured Validator()
and setting the MessageSource
.
不确定您使用的是哪个版本的 Spring Boot。我正在使用 Spring Boot 2.0.1.RELEASE
。更清晰的解决方案是将所有验证消息移动到ValidationMessages.properties
. 这样您就不必覆盖自动配置Validator()
和设置MessageSource
.
回答by A.Mushate
For rest controllers you will then have to add @Valid annotation on method parameter's request body. e.g
对于其余控制器,您必须在方法参数的请求正文上添加 @Valid 注释。例如
@PostMapping
public User create(@Valid @RequestBody User user){
//...
}
回答by Ramesh Singh
I am using 2.2.7 Release of Spring boot and it worked after me by just changing the property file name to ValidationMessages.properties and no other config required.
我正在使用 Spring boot 的 2.2.7 版本,它通过将属性文件名更改为 ValidationMessages.properties 并且不需要其他配置来在我之后工作。