从javax.validation.constraints注释不工作 [英] Annotations from javax.validation.constraints not working

查看:6768
本文介绍了从javax.validation.constraints注释不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用从 javax.validation.constraints 注释如 @Size ,<$ C $需要什么样的配置C> @NotNull ,等?这里是我的code:

What configuration is needed to use annotations from javax.validation.constraints like @Size, @NotNull, etc.? Here's my code:

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

public class Person {
      @NotNull
      private String id;

      @Size(max = 3)
      private String name;

      private int age;

      public Person(String id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
      }
}

当我尝试在其他类中使用它,验证不起作用(即没有错误创建对象):

When I try to use it in another class, validation doesn't work (i.e. the object is created without error):

Person P = new Person(null, "Richard3", 8229));

为什么没有这个申请 ID 名称限制?还有什么我需要做什么?

Why doesn't this apply constraints for id and name? What else do I need to do?

推荐答案

有关JSR-303 Bean验证的Spring工作,你需要几件事情:

For JSR-303 bean validation to work in Spring, you need several things:


    注解
  1. MVC命名空间配置:&LT; MVC:注解驱动/&GT;

  2. 的JSR-303规范JAR:验证-API 1.0.0.GA.jar (看起来像您已经有)

  3. 规范的实现,如Hibernate验证,这似乎是最常用的例如:休眠 - 验证 - 4.1.0.Final.jar

  4. 在bean来进行验证,验证的注释,无论是从规范JAR或从实现JAR(你已经做了)

  5. 在要验证处理程序,标注你想用 @Valid 来验证对象,然后包括 BindingResult 方法签名捕捉错误。

  1. MVC namespace configuration for annotations: <mvc:annotation-driven />
  2. The JSR-303 spec JAR: validation-api-1.0.0.GA.jar (looks like you already have that)
  3. An implementation of the spec, such as Hibernate Validation, which appears to be the most commonly used example: hibernate-validator-4.1.0.Final.jar
  4. In the bean to be validated, validation annotations, either from the spec JAR or from the implementation JAR (which you have already done)
  5. In the handler you want to validate, annotate the object you want to validate with @Valid, and then include a BindingResult in the method signature to capture errors.

例如:

@RequestMapping("handler.do")
public String myHandler(@Valid @ModelAttribute("form") SomeFormBean myForm, BindingResult result, Model model) {
    if(result.hasErrors()) {
      ...your error handling...
    } else {
      ...your non-error handling....
    }
}

这篇关于从javax.validation.constraints注释不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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