什么样的配置是需要使用注解来自javax.validation.constraints像@Size,@NotNull等等?这是我的代码:
javax.validation.constraints
@Size
@NotNull
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; } }
当我尝试在另一个类中使用它时,验证不起作用(即,创建该对象时没有错误):
Person P = new Person(null, "Richard3", 8229));
为什么这不适用id和的约束name?我还需要做什么?
id
name
为了使JSR-303 bean验证在Spring中起作用,你需要做一些事情:
<mvc:annotation-driven />
validation-api-1.0.0.GA.jar
hibernate-validator-4.1.0.Final.jar
@Valid
BindingResult
@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.... } }