问题
I need to get the resolved error messages programmatically in the controller. The default validation message for typeMismatch errors are not populating from my messages.properties file. I have a form backing object where a field is an Integer. If I submit a string for that field I get:
Failed to convert property value of type 'java.lang.String' to required type 'java.lang.Integer' for property 'establishedYear'; nested exception is java.lang.NumberFormatException: For input string: "1995a"
as the default message in the ObjectError. Here's my controller that output it:
@RequestMapping(method = RequestMethod.POST)
public @ResponseBody FormJSONResponse postForm(@Valid ProfileEditCompanyForm profileEditCompanyForm, BindingResult result) throws Exception {
if (result.hasErrors()) {
for (ObjectError objectError : result.getAllErrors()) {
System.out.println(objectError.getDefaultMessage()); // THIS IS NOT MY MESSAGE, BUT SHOULD BE
}
}
... other stuff ...
}
So I added a messages.properties to WEB-INF/classes with some test messages to see if I could override that default message:
typeMismatch.profileEditCompanyForm.establishedYear=test 1
typeMismatch.establishedYear=test 2
typeMismatch.java.lang.Integer=test 3
typeMismatch=test 4
profileEditCompanyForm.establishedYear=test 5
establishedYear=test 6
In my app-servlet.xml file I have:
<mvc:annotation-driven conversion-service="conversionService" validator="validator"/>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages" />
</bean>
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="validationMessageSource" ref="messageSource"/>
</bean>
Why isn't it picking up any of my messages from my messages.properties file?
回答1:
Try this in you Spring context instead:
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="WEB-INF/classes/messages" />
</bean>
Then inside "WEB-INF/classes" folder create a file call: "messages.properties"
Take note for the content of "messages.properties" you have to provide it like this :
typeMismatch.pathValueInsideYourJSPform:input= Your Message
Hope this helps you !
here is a sample also
回答2:
Try specifying the complete path and try
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="WEB-INF/messages" />
</bean>
回答3:
Apparently I have to run the FieldError objects through the Spring MessageSource. I was hoping this was done automatically. I found my answer here:
How to get error text in controller from BindingResult
来源:https://stackoverflow.com/questions/13314862/spring-validations-default-messages