Java Spring MVC 验证错误代码在哪里解决?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1881264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Where are the Spring MVC validation error codes resolved?
提问by James McMahon
I am attempting to write validatorsunder the Spring MVC framework, but there is a glaring omission in the documentation. When calling passing an error to the Errorsobject most of the methods expect an String parameter named errorCode. These errorCodes, if I understand correctly serve as stand ins for specific error messages. But I can't for the life figure out where these codes are mapped to.
我试图在 Spring MVC 框架下编写验证器,但文档中有明显的遗漏。当调用将错误传递给Errors对象时,大多数方法都需要一个名为 errorCode 的字符串参数。这些错误代码,如果我理解正确的话,可以作为特定错误消息的替代品。但我终生无法弄清楚这些代码映射到哪里。
Here is an example of what I am referring to from Spring MVC's Javadoc;
这是我从 Spring MVC 的 Javadoc 中所指的一个示例;
public class UserLoginValidator implements Validator {
private static final int MINIMUM_PASSWORD_LENGTH = 6;
public boolean supports(Class clazz) {
return UserLogin.class.isAssignableFrom(clazz);
}
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userName", "field.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "field.required");
UserLogin login = (UserLogin) target;
if (login.getPassword() != null
&& login.getPassword().trim().length() < MINIMUM_PASSWORD_LENGTH) {
errors.rejectValue("password", "field.min.length",
new Object[]{Integer.valueOf(MINIMUM_PASSWORD_LENGTH)},
"The password must be at least [" + MINIMUM_PASSWORD_LENGTH + "] characters in length.");
}
}
}
Can anyone enlighten me?
任何人都可以启发我吗?
采纳答案by Jacob Mattison
I'm using the default message resolver.
我正在使用默认的消息解析器。
In my dispatcher-servlet.xml
, I have
在我的dispatcher-servlet.xml
, 我有
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages" />
</bean>
and then in the top level of my classes directory I have a text file called "messages.properties" that contains mappings like this:
然后在我的类目录的顶层,我有一个名为“messages.properties”的文本文件,其中包含如下映射:
error.firstname.null=Please enter your first name.
error.lastname.null=Please enter your last name.
If you wanted to use a custom MessageCodesResolver you can implement the MessageCodeResolver interface and then define your resolver for a given controller like this:
如果您想使用自定义 MessageCodesResolver,您可以实现 MessageCodeResolver 接口,然后为给定的控制器定义解析器,如下所示:
<bean id="myController">
<property name="messageCodesResolver" ref="myMessageCodesResolver" />
</bean>
There isn't currently a way to define a custom MessageCodeResolver
globally; there's an enhancement request for that here. One approach using bean inheritance to make all controller beans inherit from one controller bean definition, is described here.
目前没有办法MessageCodeResolver
全局定义自定义;这里有一个增强请求。此处描述了一种使用 bean 继承使所有控制器 bean 从一个控制器 bean 定义继承的方法。
回答by matt b
They are resolved by your MessageSourceand a MessagesCodeResolver.
它们由您的MessageSource和MessagesCodeResolver解析。
Hereis the relevant section in the reference manual:
这是参考手册中的相关部分:
Outputting messages corresponding to validation errors is the last thing we need to discuss. In the example we've shown above, we rejected the name and the age field. If we're going to output the error messages by using a
MessageSource
, we will do so using the error code we've given when rejecting the field ('name' and 'age' in this case). When you call (either directly, or indirectly, using for example theValidationUtils
class)rejectValue
or one of the other reject methods from theErrors
interface, the underlying implementation will not only register the code you've passed in, but also a number of additional error codes.
输出与验证错误对应的消息是我们需要讨论的最后一件事。在我们上面显示的示例中,我们拒绝了 name 和 age 字段。如果我们要使用 a 输出错误消息
MessageSource
,我们将使用我们在拒绝字段时给出的错误代码(在本例中为“name”和“age”)。当您从接口调用(直接或间接,例如使用ValidationUtils
类)rejectValue
或其他拒绝方法之一时Errors
,底层实现不仅会注册您传入的代码,还会注册一些额外的错误代码.
回答by Umesh Rajbhandari
For some reason if you want to resolve the messages in the Controller similar to form:errors jsp tags then you can do the following:
出于某种原因,如果您想解决 Controller 中类似于 form:errors jsp 标签的消息,那么您可以执行以下操作:
//result is BindingResult
List<String> errors = new ArrayList<String>();
List<ObjectError> allErrors = result.getAllErrors();
for (ObjectError error : allErrors) {
String message = messageSource.getMessage(error, null);
errors.add(message);
}