Resolving Codes to Error Messages

我们介绍了数据绑定和验证。本节介绍输出与验证错误相对应的消息。在preceding section中所示的示例中,我们拒绝了`name`和`age`字段。如果我们想使用`MessageSource`输出错误消息,我们可以使用我们在拒绝该字段时提供的错误代码(在本例中为“name”和“age”)执行此操作。当您调用(直接或间接地,例如,通过使用`ValidationUtils`类)rejectValue`或`Errors`接口中的其他`reject`方法时,底层实现不仅注册了您传递的代码,还注册了许多其他错误代码。`MessageCodesResolver`确定`Errors`接口将注册哪些错误代码。默认情况下,会使用`DefaultMessageCodesResolver,它(例如)不仅会注册一个包含您给定的代码的消息,还会注册包含您传递到 reject 方法的字段名称的消息。因此,如果您使用`rejectValue("age", "too.darn.old")拒绝一个字段,除了`too.darn.old`代码外,Spring 还注册`too.darn.old.age`和`too.darn.old.age.int(第一个包括字段名称,第二个包括字段类型)。这样做是为了方便开发人员在定位错误消息时使用。

We covered databinding and validation. This section covers outputting messages that correspond to validation errors. In the example shown in the preceding section, we rejected the name and age fields. If we want to output the error messages by using a MessageSource, we can do so using the error code we provide when rejecting the field ('name' and 'age' in this case). When you call (either directly, or indirectly, by using, for example, the ValidationUtils class) rejectValue or one of the other reject methods from the Errors interface, the underlying implementation not only registers the code you passed in but also registers a number of additional error codes. The MessageCodesResolver determines which error codes the Errors interface registers. By default, the DefaultMessageCodesResolver is used, which (for example) not only registers a message with the code you gave but also registers messages that include the field name you passed to the reject method. So, if you reject a field by using rejectValue("age", "too.darn.old"), apart from the too.darn.old code, Spring also registers too.darn.old.age and too.darn.old.age.int (the first includes the field name and the second includes the type of the field). This is done as a convenience to aid developers when targeting error messages.

有关`MessageCodesResolver`和默认策略的更多信息,请分别参见https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/validation//MessageCodesResolver.html[MessageCodesResolver] 和https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/validation//DefaultMessageCodesResolver.html[DefaultMessageCodesResolver] 的 javadoc。

More information on the MessageCodesResolver and the default strategy can be found in the javadoc of MessageCodesResolver and DefaultMessageCodesResolver, respectively.