Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Spring's MessageSource for setting FieldError default messages

After my form backing object is validated I have a BindingResult, which contains a list of FieldError. Each FieldError has a defaultMessage. How is that message set and why doesn't it use my Spring MessageSource? I would like that default message to be derived from my Spring's MessageSource.

EDIT: I see that the error codes are being set correctly in the FieldError object. It's just the default message in that object is not coming from my MessageSource. For instance, when I enter a string for a field that is an int I want it to get my message from messages.properties:

typeMismatch=Invalid type was entered.

The only way I can get that message is if I take my FieldError object and pass it into the MessageSource manually like so:

messageSource.getMessage(fieldError, null);  // This gets my message from messages.properties.
like image 272
Jeremy Avatar asked Oct 22 '22 03:10

Jeremy


1 Answers

If you're using a Validator, you can specify the keys for the messages in the MessageSource in the Validator implementing class, usually using ValidationUtils methods. Section 6.2 of the Spring documentation has a good example.

Spring will also try to resolve error codes by convention if you're using something other than a Validator like JSR-303 Bean Validation.

Let's say you had a form backing object called 'Address' with an int field called 'zipcode.' If the user entered a string for the zipcode field, by default Spring will use the DefaultMessageCodesResolver and look in the MessageSource for a key called 'typeMismatch.address.zipcode.' If it doesn't find that key, it will try 'typeMismatch.zipcode,' then 'typeMismatch.int,' then 'typeMismatch.'

Or, you can implement your own MessageCodesResolver.

like image 72
dvause Avatar answered Oct 27 '22 09:10

dvause