gpt4 book ai didi

java - javax.validation.constraints 中的注释不起作用

转载 作者:IT老高 更新时间:2023-10-28 13:03:26 47 4
gpt4 key购买 nike

使用 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));

为什么这不对 idname 应用约束?我还需要做什么?

最佳答案

要让 JSR-303 bean 验证在 Spring 中工作,您需要做几件事:

  1. 注解的 MVC 命名空间配置:<mvc:annotation-driven />
  2. JSR-303 规范 JAR:validation-api-1.0.0.GA.jar (看起来你已经有了)
  3. 规范的实现,例如 Hibernate Validation,这似乎是最常用的示例:hibernate-validator-4.1.0.Final.jar
  4. 在要验证的 bean 中,验证注释,来自规范 JAR 或来自实现 JAR(您已经完成)
  5. 在要验证的处理程序中,使用 @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....
}
}

关于java - javax.validation.constraints 中的注释不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8756768/

47 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com