Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

bean validation - Spring Boot JSR303 message code in annotation getting ignored

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...