use*_*124 8 bean-validation spring-boot
在我的Spring Boot应用程序中,我有一个支持bean,我正在使用JSR303验证.在注释中,我指定了消息代码:
@NotBlank(message = "{firstname.isnull}")
private String firstname;
Run Code Online (Sandbox Code Playgroud)
然后在我的message.properties中我指定:
firstname.isnull = Firstname cannot be empty or blank
Run Code Online (Sandbox Code Playgroud)
我对MessageSource的JavaConfig是:
@Bean(name = "messageSource")
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
Run Code Online (Sandbox Code Playgroud)
验证工作正常,但我没有看到实际的字符串,而是在我的jsp页面中获取消息代码.在查看日志文件时,我看到一组代码:
Field error in object 'newAccount' on field 'firstname': rejected value []; codes [NotBlank.newAccount.firstname,NotBlank.firstname,NotBlank.java.lang.String,NotBlank]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [newAccount.firstname,firstname]; arguments []; default message [firstname]]; default message [{firstname.isnull}]
Run Code Online (Sandbox Code Playgroud)
如果我将message.properties中的消息代码更改为数组中的某个代码,则该字符串将在我的Web表单中正确显示.我甚至不必更改注释中的代码.这向我指示注释的message参数中的代码被忽略.
我不想使用默认代码.我想用自己的.我怎样才能做到这一点.能否请您提供代码示例.
JSR303插值通常适用于ValidationMessages.properties文件.但是你可以配置Spring来改变它,如果你想(我很懒,这样:))例如
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="validationMessageSource" ref="messageSource" />
</bean>
<mvc:annotation-driven validator="validator" />
Run Code Online (Sandbox Code Playgroud)
根据JSR-303规范,消息参数预计存储在ValidationMessages.properties文件中.但是你可以覆盖他们寻找的地方.
所以你有两个选择:
ValidationMessages.properties文件或覆盖getValidator()你WebMvcConfigurerAdapter的后代的方法(JavaConfig在你的情况下):
@Override
public Validator getValidator() {
LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
validator.setValidationMessageSource(messageSource());
return validator;
}
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
7734 次 |
| 最近记录: |