Override Spring form error messages

In Spring, how to override default form error arrays?

I also use Validator

a properties file to add my own error messages, but how do I override the messages that are printed when a conversion / encoding error occurs, for example?

They seem to be generated automatically and I don't think they are useful to the user:

Failed to convert property value of type java.lang.String to required type java.lang.Double for property minPrice; nested exception is java.lang.NumberFormatException: 

      

+3


source to share


1 answer


You can override the defaults by creating custom messages in your localization pack with keys following with the conventions defined by Spring DefaultMessageCodeResolver

. For completeness, here's the relevant portion of its documentation:



Generates two message codes for an object error, in the following order (using prefix formatting):

1.: code + "." + object name
2.: code 

      

Generates four message codes for the field specification, in the following order:

1.: code + "." + object name + "." + field
2.: code + "." + field
3.: code + "." + field type
4.: code 

      

For example, in the case of the code "typeMismatch", object name "user", field "Age":

1. try "typeMismatch.user.age"
2. try "typeMismatch.age"
3. try "typeMismatch.int"
4. try "typeMismatch" 

      

Thus, this resolution algorithm can be used, for example, to show specific messages for errors such as "required" and "TypeMismatch":

at the object + field level ("age" field, but only on "user");
at the field level (all "age" fields, no matter which object name);
or at the general level (all fields, on any object). 

      

In the case of array, list, or map properties, both codes are generated for specific elements and for the entire collection. Assuming field "array name" group "in object" user ":

1. try "typeMismatch.user.groups[0].name"
2. try "typeMismatch.user.groups.name"
3. try "typeMismatch.groups[0].name"
4. try "typeMismatch.groups.name"
5. try "typeMismatch.name"
6. try "typeMismatch.java.lang.String"
7. try "typeMismatch" 

      

By default, error codes will be placed at the beginning of the constructed message lines. The messageCodeFormatter property can be used to specify an alternative concatenation format.

To group all codes into a specific category within resource packs, for example. "validation.typeMismatch.name" instead of the default "typeMismatch.name", consider adding a prefix attached.

+5


source







All Articles