Spring Validation模塊用於表單數據驗證配置,示例如下
依賴Jar包
<dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> </dependency>
Controller方法
/** * 添加酒店 * @param hotel * @param bindingResult * @return */ @RequestMapping(value = "/add") // @Valid注釋表示需要驗證 public String addHotel(@Valid Hotel hotel, BindingResult bindingResult, Model model) { if (hotel.getName() == null) { // 顯示添加頁面 model.addAttribute(HOTEL, new Hotel()); return "hotel/addHotel"; } else { // 驗證失敗時回到本頁面並顯示錯誤信息 if (bindingResult.hasErrors()) return "hotel/addHotel"; hotelService.addHotel(hotel); return "redirect:/hotel/list"; } }
需要驗證的bean配置
package com.qunar.bean; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.NotEmpty; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; public class Hotel { private Integer id; @NotNull(message = "酒店代碼不能為空") @NotEmpty(message = "酒店代碼不能為空") @Pattern(regexp = "\\w+", message = "酒店代碼不能包含特殊字符") @Length(max = 45, message = "酒店代碼最長為45個字符") private String code; @NotNull(message = "酒店名稱不能為空") @NotEmpty(message = "酒店名稱不能為空") @Pattern(regexp = "([\\u4e00-\\u9fa5]|\\w)+", message = "酒店名稱不能包含特殊字符") @Length(max = 100, message = "酒店名稱最長為100個字符") private String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code == null ? null : code.trim(); } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } }
頁面
<%-- Created by IntelliJ IDEA. User: zhenwei.liu Date: 13-7-30 Time: 上午11:50 To change this template use File | Settings | File Templates. --%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form" %> <%@ page contentType="text/html;charset=UTF-8" pageEncoding="utf-8" %> <html> <head> <title>添加酒店</title> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> </head> <body> <sf:form action="/hotel/add" method="POST" modelAttribute="hotel"> <table> <tr> <td align="right">酒店代碼</td> <td><input type="text" name="code"/></td> <td><sf:errors path="code" cssClass="error" /> </td> </tr> <tr> <td align="right">酒店名稱</td> <td><input type="text" name="name"/></td> <td><sf:errors path="name" cssClass="error" /> </td> </tr> <tr> <td colspan="2" align="center"><input type="submit" value="添加"/> <input type="reset" value="重置"/></td> </tr> </table> </sf:form> </body> </html>
這樣當提交這個這個頁面表單時,就會驗證hotel的各個屬性,如驗證不通過則回到本頁面並顯示錯誤信息
另外,Spring支持自定義驗證注解類,加入自己的驗證規則,具體例子可以參考以下
http://outbottle.com/custom-annotated-validation-with-spring-3-web-mvc/