1.使用JSR303标準
1.1 JSR 303 是 Java 為 Bean 資料合法性校驗提供的标準架構,它已經包含在 JavaEE 6.0 中 .
1.2 JSR 303 通過在 Bean 屬性上标注類似于 @NotNull、@Max等标準的注解指定校驗規則,
并通過标準的驗證接口對 Bean進行驗證

2.應為JSR303隻是一個标準,是以如果想使用這套标準進行驗證,需要有一個實作該标準的産品。
Hibernate Validator驗證架構
2.1 Hibernate Validator 是 JSR 303 的一個參考實作,除支援所有标準的校驗注解外,它還支援以下的擴充注解
2.2 加入hibernate-validator的jar包
3. 在spring.xml配置檔案中添加 <mvc:annotation-driven></mvc:annotation-driven>
4. 在需要驗證的屬性上添加對應的直接。
@NotEmpty //不能為空
private String lastName;
@Email //郵件
private String email;
@Past //不能是過去的時間
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date birth;
5.在目标方法bean類型的前面添加 @Valid 注解(注意解決jar包的沖突)。其中,由于配置了
<mvc:annotation-driven></mvc:annotation-driven>會按照注解自動完成資料類型的轉換和格式化,如果中間
出現轉換的錯誤,會自動将錯誤資訊加入到 BindingResult該參數中,可以通過添加BindingResult參數,擷取錯誤
資訊。
@RequestMapping(value="/emp",method=RequestMethod.POST)
public String save(@Valid Employee employee,BindingResult result){
System.out.println(employee);
if (result.getErrorCount() > 0) {
for (FieldError error : result.getFieldErrors()) {
System.out.println(error.getField() + ":"
+ error.getDefaultMessage());
}
}
employeeDao.save(employee);
return "redirect:/emps";
}
6. 如果驗證出錯,跳轉到指定的頁面。(傳回到原來的填寫頁面,會自動回顯内容,但是下拉清單框的内容需要放入map
傳到前台。)
@RequestMapping(value="/emp",method=RequestMethod.POST)
public String save(@Valid Employee employee,BindingResult result,Map<String,Object> map){
System.out.println(employee);
if (result.getErrorCount() > 0) {
for (FieldError error : result.getFieldErrors()) {
System.out.println(error.getField() + ":"+ error.getDefaultMessage());
}
map.put("departments", departmentDao.getDepartments());
return "input";
}
employeeDao.save(employee);
return "redirect:/emps";
}