First Approach:
Use JSR-303 annotations
Requirement: Spring 3.x
example:
public class MyClass {
@NotNull
private String name;
@NotEmpty @Email //需要Hibernate Validator
private String email;
@NotNull @Min(18) @Max(65)
private Integer age;
}
In spring controller method add @Valid before your classes/parameter
example:
@RequestMapping("myPath")
public void handleRequest(Model model,
@Valid @ModelAttribute("myClass") MyClass myClass,
BindingResult result) {
if(result.hasErrors()) {
// validation fail, do something
}
//validation success, other code
}
Pros : fast and easy, validate object according to annotation inside MyClass
Cons: Can only used on binding object, we can not use it on primitive data type.
Cons: Can only used on binding object, we can not use it on primitive data type.
____________________________________________________________________________
Second Approach:
Use A separate Validator component or service (@Component/@Service)
You have to create : a Validator class implements springframework.validation.Validator
In controller
@Autowired
private MyValidator myValidator;
@Autowired
private OtherValidator otherValidator;
example:
@RequestMapping("myPath")
public void handleRequest(Model model,
@ModelAttribute("myClass") MyClass myClass,
BindingResult result) {
myValidator.validate(myClass, result);
if(result.hasErrors()) {
// validation fail, do something
}
otherValidator.validate(myParam, result);
if(result.hasErrors()) {
// validation fail, do something
}
//validation success, other code
}
Pros: Handle complex validation, can bind with other component/service in validator.
____________________________________________________________________________
Third Approach by creating a BindingResult in Controller:
If you can not get a BindingResult (Not using a form object), the binding result can be accessed by DataBinder class :
example (Tested) :
In your mapping function :
DataBinder binder = new DataBinder(MyObject);
binder.setValidator(MyObjectValidator);
binder.validate();
BindingResult results = binder.getBindingResult();
if(results.hasErrors()) {
//handle your error
}else {
//do your work
}
Pros: Free from the BindingResult restrictions.
Cons: Not a neat coding.
詳細資料及來源:
https://stackoverflow.com/questions/12146298/spring-mvc-how-to-perform-validation/12149331#12149331?newreg=939c481aded644119cfdcf43a48718bb
後感:
Spring validation 也很有MVC的特色, 分門別類很清楚, 可惜只可以用係request object上, 如果只得一個primitive要拎就唯有form object, 或者用DataBinder拎BindingResult
沒有留言:
張貼留言