In my Spring Boot app I have a backing bean where I am using JSR303 validation. In the annotation, I have specified the message code:
@NotBlank(message = "{firstname.isnull}")
private String firstname;
Then in my message.properties I have specified:
firstname.isnull = Firstname cannot be empty or blank
My JavaConfig for the messageSource is:
@Bean(name = "messageSource")
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
The validation works correctly but instead of seeing the actual string, I get the message code in my jsp page. In looking at the log file, I see an array of codes:
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}]
If I change the my message code in the message.properties to one of the codes in the array, the string displays correctly in my web form. I didn't even have to change the code in the annotation. This indicates to me the code in the message parameter of the annotation is getting ignored.
I don't want to use the default code. I want to use my own. How can I make this work. Can you please provide a code example.
JSR303 interpolation normally works with ValidationMessages.properties
file. However you can configure Spring to change that if you want (I was lazy to do so :)) e.g.
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="validationMessageSource" ref="messageSource" />
</bean>
<mvc:annotation-driven validator="validator" />
According to JSR-303 specification message parameters are expected to be stored in ValidationMessages.properties
files. But you can override the place where they are looked for.
So you have 2 options:
ValidationMessages.properties
fileOr override getValidator()
method of your WebMvcConfigurerAdapter
's descendant (JavaConfig
in your case):
@Override
public Validator getValidator() {
LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
validator.setValidationMessageSource(messageSource());
return validator;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With