Spring MVC使用hibernate Validator来验证单个基本类型 [英] Spring MVC with hibernate Validator to validate single basic type

查看:662
本文介绍了Spring MVC使用hibernate Validator来验证单个基本类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我遇到问题的映射方法,无论我传递给它的值是什么,验证都会返回通过验证。

Below is the mapped method that I am having trouble with, no matter what value I pass to it the validation returns "passed validation."

@RequestMapping(value = "test", method = RequestMethod.POST)
@ResponseBody
public String getTest(@RequestBody @Valid @Max(32) long longValue, BindingResult result) {
  if (result.hasErrors()) {
    return "failed validation";
  } else {
    return "passed validation";
  }
}

我知道@Max适用于我的应用程序,因为我用它来验证将大量数据返回给控制器的自定义对象。它只是在这种情况下不运行验证,我调用@Valid和方法参数中对象的验证类型。

I know the @Max works with my application because I use it for validation on custom objects that return a lot of data to the controller. It only doesn't run the validation in this case where I call @Valid and the type of validation on the object in the method parameters.

hibernate不允许这样做-验证器?

Is this not allowed with hibernate-validator?

我希望不必定义一个只包含长值的对象,以便我可以对其进行验证。

I am hoping to not have to define an object that only contains a long value just so that I can run validation on it.

推荐答案


我希望不必定义一个只包含long
值的对象,以便我可以运行验证在它上面。

I am hoping to not have to define an object that only contains a long value just so that I can run validation on it.

定义一个包装bean将是最聪明的举动,因为hibernate-validator完全围绕bean的概念。毕竟,它是bean验证规范的参考实现。该规范的主要推动者之一是承认验证是跨越不同应用层的跨领域关注点,并提供一种优雅地处理此问题的机制。这就是为什么它以bean为中心,它是通过层的对象。

Defining a wrapping bean would IMHO be the smartest move, as hibernate-validator is completly centered around the notion of the bean, and is, after all, a reference implementation of the bean validation specification. One of the primary motivators of the spec is to acknowledge validation as a cross-cutting concern that spans across different app layers, and provide a mechanism to gracefully handle this. That is the reason why it is centered around beans, its the objects that get passed through the layers.

另一方面,在程序上验证原始数据并不是什么大不了的事,你的代码可能就像

On the other hand, validating primitves programtically is not a big deal after all, your code can simply be something like

@RequestMapping(value = "test", method = RequestMethod.POST)
@ResponseBody
public String getTest(@RequestBody long longValue, BindingResult result) {
  if (longValue > 32) {
     result.rejectValue("longValue", "error.longValue", "longValue max constrained failed");
    return "failed validation";
  } else {
    return "passed validation";
  }
}

所以在我看来,要么进行程序验证如果它足够简单,或者只是包装值。

So in my opinion, either go for the programatic validation if its simple enough, or simply wrap the value.

这篇关于Spring MVC使用hibernate Validator来验证单个基本类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆