Annotations from javax.validation.constraints not working(javax.validation.constraints 中的注释不起作用)
问题描述
使用 javax.validation.constraints 中的注解(如 @Size、@NotNull 等)需要什么配置?这是我的代码:
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 和 name 应用约束?我还需要做什么?
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:
- 注解的MVC命名空间配置:
<mvc:annotation-driven/> - JSR-303 规范 JAR:
validation-api-1.0.0.GA.jar(看起来你已经有了) - 规范的实现,例如 Hibernate Validation,这似乎是最常用的示例:
hibernate-validator-4.1.0.Final.jar - 在要验证的 bean 中,验证注释,来自规范 JAR 或来自实现 JAR(您已经完成)
 - 在您要验证的处理程序中,使用
@Valid注释您要验证的对象,然后在方法签名中包含一个BindingResult以捕获错误. 
- MVC namespace configuration for annotations: 
<mvc:annotation-driven /> - The JSR-303 spec JAR: 
validation-api-1.0.0.GA.jar(looks like you already have that) - 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 - In the bean to be validated, validation annotations, either from the spec JAR or from the implementation JAR (which you have already done)
 - In the handler you want to validate, annotate the object you want to validate with 
@Valid, and then include aBindingResultin 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 中的注释不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:javax.validation.constraints 中的注释不起作用
				
        
 
            
        基础教程推荐
- 不推荐使用 Api 注释的描述 2022-01-01
 - 验证是否调用了所有 getter 方法 2022-01-01
 - 大摇大摆的枚举 2022-01-01
 - 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
 - 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
 - Java 实例变量在两个语句中声明和初始化 2022-01-01
 - 多个组件的复杂布局 2022-01-01
 - 在 Java 中创建日期的正确方法是什么? 2022-01-01
 - 从 python 访问 JVM 2022-01-01
 - Java Swing计时器未清除 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				