Spring MVC 验证错误代码在哪里解决?

发布于 2024-08-14 09:27:23 字数 1429 浏览 6 评论 0原文

我正在尝试编写 验证器 Spring MVC框架下的,但是文档中有明显的遗漏。调用时将错误传递给 Errors 对象 大多数方法都需要一个名为 errorCode 的字符串参数。如果我理解正确的话,这些错误代码可以作为特定错误消息的替代。但我一生都无法弄清楚这些代码映射到哪里。

这是我从 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.");
       }
    }
 }

谁能启发我吗?

I am attempting to write validators under the Spring MVC framework, but there is a glaring omission in the documentation. When calling passing an error to the Errors object 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.

Here is an example of what I am referring to from Spring MVC's 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

始终不够爱げ你 2024-08-21 09:27:23

我正在使用默认的消息解析器。

在我的 dispatcher-servlet.xml 中,我

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename" value="messages" />
</bean>

其中包含如下映射:

error.firstname.null=Please enter your first name.
error.lastname.null=Please enter your last name.

有一个名为“messages.properties”的文本文件, 自定义 MessageCodesResolver 您可以实现 MessageCodeResolver 接口,然后为给定控制器定义解析器,如下所示:

<bean id="myController">
  <property name="messageCodesResolver" ref="myMessageCodesResolver" />
</bean>

目前还没有一种方法可以全局定义自定义 MessageCodeResolver此处有一个增强请求这里描述了一种使用 bean 继承使所有控制器 bean 继承一个控制器 bean 定义的方法

I'm using the default message resolver.

In my dispatcher-servlet.xml, I have

<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:

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:

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

画▽骨i 2024-08-21 09:27:23

它们由您的 MessageSource 和 MessagesCodeResolver

这里是相关部分参考手册:

输出与验证错误相对应的消息是我们需要讨论的最后一件事。在上面显示的示例中,我们拒绝了姓名和年龄字段。如果我们要使用 MessageSource 输出错误消息,我们将使用拒绝字段时给出的错误代码(本例中为“name”和“age”) 。当您调用(直接或间接,例如使用 ValidationUtils 类)rejectValue 或来自 Errors 接口的其他拒绝方法之一时,底层实现不仅会注册您传入的代码,还会注册一些额外的错误代码。

They are resolved by your MessageSource and a MessagesCodeResolver.

Here is 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 the ValidationUtils class) rejectValue or one of the other reject methods from the Errors interface, the underlying implementation will not only register the code you've passed in, but also a number of additional error codes.

〃温暖了心ぐ 2024-08-21 09:27:23

由于某种原因,如果您想解析控制器中类似于 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);
   }

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:

   //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);
   }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文