5

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.
4

1 回答 1

3

如果您使用的是Validator,则可以在 Validator 实现类的 MessageSource 中指定消息的键,通常使用 ValidationUtils 方法。Spring 文档的第 6.2 节有一个很好的例子。

如果您使用的不是 Validator(如 JSR-303 Bean Validation),Spring 也会尝试按照约定解决错误代码。

假设您有一个名为“地址”的表单支持对象,其中包含一个名为“邮政编码”的 int 字段。如果用户为 zipcode 字段输入了字符串,默认情况下 Spring 将使用DefaultMessageCodesResolver并在 MessageSource 中查找名为“typeMismatch.address.zipcode”的键。如果它没有找到那个键,它将尝试“typeMismatch.zipcode”,然后是“typeMismatch.int”,然后是“typeMismatch”。

或者,您可以实现自己的MessageCodesResolver

于 2012-11-10T02:37:54.990 回答