本文介紹了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 aBindingResult
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 中的注釋不起作用的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!