且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Spring MVC使用hibernate Validator来验证单个基本类型

更新时间:2022-11-21 20:41:16


我希望不必定义一个只包含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.