SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-007-表单验证@Valid、Error

一、

Starting with Spring 3.0, Spring supports the Java Validation API in Spring MVC . No extra configuration is required to make Java Validation work in Spring MVC . You just need to make sure an implementation of the Java API , such as Hibernate Validator, is in the project’s classpath.

1.

2.在实体类写约束

 1 public class Spitter {
 2 
 3   private Long id;
 4   
 5   @NotNull
 6   @Size(min=5, max=16)
 7   private String username;
 8 
 9   @NotNull
10   @Size(min=5, max=25)
11   private String password;
12   
13   @NotNull
14   @Size(min=2, max=30)
15   private String firstName;
16 
17   @NotNull
18   @Size(min=2, max=30)
19   private String lastName;
20   
21   @NotNull
22   @Email
23   private String email;

3.controller中

1 @RequestMapping(value="/register", method=POST)
2   public String processRegistration(
3       @Valid Spitter spitter, 
4       Errors errors) {
5     if (errors.hasErrors()) {
6       return "registerForm";
7     }

 

posted @ 2016-03-04 17:40  shamgod  阅读(322)  评论(0编辑  收藏  举报
haha