1. 程式人生 > >資料校驗框架

資料校驗框架

(參考:http://blog.csdn.net/yang_hui_liang/article/details/79133252

http://blog.csdn.net/yang_hui_liang/article/details/79133173)

資料校驗框架

Spring 3.0擁有直接獨立的資料校驗框架,同時支援JSR 303標準的校驗框架,spring的DataBinder在進行資料繫結時,可以同時呼叫校驗框架完成資料校驗工作。在Spring MVC中,則可以直接通過註解驅動的方式進行資料校驗。

Spring的org.springframework.validation是校驗框架所在的包。

JSR 303

JSP 303是java為Bean資料合法性校驗所提供的標準框架,它已經包含在java EE 6.0。JSR 303通過Bean屬性上標註類似於@NotNull、@Max等標準的註解指定校驗規則,並通過標準的驗證介面對Bean進行驗證。

你可以通過http://jcp.org/en/jsr/detail?id=3030瞭解JSP 303 的詳細內容。




資料校驗框架

<mvc:annotation-driven/>會預設裝配好一個LocalValidatorFactoryBean,通過在處理方法的入參上標註@Valid註解既可讓Spring MVC在完成資料繫結後執行資料校驗的工作


public class User {     
      @Pattern(regexp="w{4,30}")  
      private String userName;  
      
      @Length(min=2,max=100)  
      private String realName;  
      
     @Past   
     @DateTimeFormat(pattern="yyyy-MM-dd")  
     private Date birthday;  
      
    @DecimalMin(value="1000.00")  
    @DecimalMax(value="100000.00")   
    @NumberFormat(pattern="#,###.##")  
    private long salary;  
}  


注意:Spring本身沒有提供JSR 303的實現,所以必須將JSR 303的實現者(如Hibernate Validator)的jar檔案放到類路徑下,Spring將自動載入並裝配好JSR 303的實現者。


如何使用註解驅動的校驗

@Controller  
public class UserController {  
     @RequestMapping(value = "/handle91")  
     public String handle91(@Valid  User user,BindingResult bindingResult){       
          if(bindingResult.hasErrors()){  
               return "/user/register3";  
          }else{  
               return "/user/showUser";  
          }  
    }  


在已經標註了JSR 303註解的表單/命令物件前標註一個@Valid,Spring MVC框架在將請求資料繫結到該入參物件後,就會呼叫校驗框架根據註解宣告的校驗規則實施校驗。
使用校驗功能時,處理方法要如何簽名?





Spring MVC是通過對處理方法簽名的規約來儲存校驗結果的:前一個表單/命令物件的校驗結果儲存在其後的入參中,這個儲存校驗結果的入參必須是BindingResult或Errors型別,這兩個類都位於org.springframework.validation包中。




校驗錯誤訊息存放位置




4.Spring將HttpServletRequest物件資料繫結到處理方法的入參物件中(表單/命令物件);

5.將繫結錯誤訊息、檢驗錯誤訊息都儲存到隱含模型中;

6.本次請求的對應隱含模型資料存放到HttpServletRequest的屬性列表中,暴露給檢視物件。


頁面如何顯示錯誤訊息
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>  
<%@ taglib prefix="c"      uri="http://java.sun.com/jsp/jstl/core" %>     
<%@ taglib prefix="form"   uri="http://www.springframework.org/tags/form" %>  
<html>  
<head>  
<title>註冊使用者</title>  
  <style>.errorClass{color:red}</style>  
</head>  
<body>   
  <form:form modelAttribute="user"  action="user/handle91.html">  
      <form:errors path="*"/>  
      <table>  
        <tr>  
           <td>使用者名稱:</td>  
           <td>  
              <form:errors path="userName" cssClass="errorClass"/>  
              <form:input path="userName" />  
           </td>  
        </tr>  
           …          
    </table>  
  </form:form>  
</body>  
</html>  

示例:

所需jar包

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  
  <modelVersion>4.0.0</modelVersion>  
  <groupId>cn.et</groupId>  
  <artifactId>SpringMvc_Verify</artifactId>  
  <version>0.0.1-SNAPSHOT</version>  
  <packaging>war</packaging>  
  <name/>  
   <dependencies>  
    <!-- springmvc依賴 -->  
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-webmvc</artifactId>  
        <version>4.2.0.RELEASE</version>  
    </dependency>  
    <!--jsr303驗證框架 -->  
    <dependency>  
        <groupId>org.hibernate</groupId>  
        <artifactId>hibernate-validator</artifactId>  
        <version>4.3.2.Final</version>  
    </dependency>  
    <!-- https://mvnrepository.com/artifact/net.sf.json-lib/json-lib -->  
    <dependency>  
        <groupId>net.sf.json-lib</groupId>  
        <artifactId>json-lib</artifactId>  
        <version>2.4</version>  
        <classifier>jdk15</classifier>  
    </dependency>  
    <!-- 新增jackson的json解析器 -->  
    <dependency>  
        <groupId>com.fasterxml.jackson.core</groupId>  
        <artifactId>jackson-databind</artifactId>  
        <version>2.8.9</version>  
    </dependency>  
    <dependency>  
        <groupId>org.codehaus.jackson</groupId>  
        <artifactId>jackson-mapper-asl</artifactId>  
        <version>1.9.13</version>  
    </dependency>  
      
      
    <dependency>  
      <groupId>org.apache.openejb</groupId>  
      <artifactId>javaee-api</artifactId>  
      <version>5.0-1</version>  
      <scope>provided</scope>  
    </dependency>  
    <dependency>  
      <groupId>javax.faces</groupId>  
      <artifactId>jsf-api</artifactId>  
      <version>1.2_04</version>  
      <scope>provided</scope>  
    </dependency>  
    <dependency>  
      <groupId>javax.servlet</groupId>  
      <artifactId>jstl</artifactId>  
      <version>1.2</version>  
      <scope>provided</scope>  
    </dependency>  
    <dependency>  
      <groupId>javax.servlet.jsp</groupId>  
      <artifactId>jsp-api</artifactId>  
      <version>2.1</version>  
      <scope>provided</scope>  
    </dependency>  
    <dependency>  
      <groupId>javax.faces</groupId>  
      <artifactId>jsf-impl</artifactId>  
      <version>1.2_04</version>  
      <scope>provided</scope>  
    </dependency>  
  </dependencies>  
  <build>  
    <sourceDirectory>${basedir}/src</sourceDirectory>  
    <outputDirectory>${basedir}/WebRoot/WEB-INF/classes</outputDirectory>  
    <resources>  
      <resource>  
        <directory>${basedir}/src</directory>  
        <excludes>  
          <exclude>**/*.java</exclude>  
        </excludes>  
      </resource>  
    </resources>  
    <plugins>  
      <plugin>  
        <artifactId>maven-war-plugin</artifactId>  
        <configuration>  
          <webappDirectory>${basedir}/WebRoot</webappDirectory>  
          <warSourceDirectory>${basedir}/WebRoot</warSourceDirectory>  
        </configuration>  
      </plugin>  
      <plugin>  
        <artifactId>maven-compiler-plugin</artifactId>  
        <configuration>  
          <source>1.5</source>  
          <target>1.5</target>  
        </configuration>  
      </plugin>  
    </plugins>  
  </build>  
</project>  

web.xml配置

<?xml version="1.0" encoding="UTF-8"?>  
<web-app version="2.5"   
    xmlns="http://java.sun.com/xml/ns/javaee"   
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
      
    <!-- 在使用springmvc的標籤或者國際化中 都需要spring的支援  指定spring配置檔案位置-->  
    <context-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>classpath:/spring.xml</param-value>  
    </context-param>  
    <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
    </listener>  
  <!-- 請求method支援put和delete必須新增過濾器 -->  
    <filter>  
        <filter-name>myFile</filter-name>  
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>  
    </filter>  
    <filter-mapping>  
        <filter-name>myFile</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>  
  <welcome-file-list>  
    <welcome-file>index.jsp</welcome-file>  
  </welcome-file-list>  
    
  <!--  
        解決亂碼的配置    使用攔截器攔截/*所有路徑,將請求頭和響應頭都設定為UTF-8 
    -->  
<filter>  
    <filter-name>encodingFilter</filter-name>  
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
    <init-param>  
        <!-- 設定request 字符集 -->  
        <param-name>encoding</param-name>  
        <param-value>UTF-8</param-value>  
    </init-param>  
    <init-param>  
        <!-- 設定response 字符集 -->  
        <param-name>forceEncoding</param-name>  
        <param-value>true</param-value>  
    </init-param>  
</filter>  
<filter-mapping>  
    <filter-name>encodingFilter</filter-name>  
    <url-pattern>/*</url-pattern>  
</filter-mapping>  
    
    
   <!-- 配置springmvc的核心控制器  將uri攔截下來 -->  
    <servlet>  
        <servlet-name>mvc</servlet-name>  
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
        <load-on-startup>1</load-on-startup>  
    </servlet>  
    <servlet-mapping>  
        <servlet-name>mvc</servlet-name>  
        <url-pattern>/</url-pattern>  
    </servlet-mapping>  
    <welcome-file-list>  
        <welcome-file>index.jsp</welcome-file>  
    </welcome-file-list>  
</web-app>  

springmvc.xml配置

<?xml version="1.0" encoding="UTF-8"?>  
<beans  
    xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns:p="http://www.springframework.org/schema/p"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xsi:schemaLocation="  
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd  
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd  
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd  
    ">  
  <!-- 指定掃描的位置 -->    
  <context:component-scan base-package="cn"></context:component-scan>  
   <!-- springmvc 配置攔截  / 所有資源都被攔截 圖片無法展示  將除控制層以外的資源交回給servlet處理 -->  
    <mvc:default-servlet-handler/>  
    <!-- 將springmvc註解的action交給springmvc處理 -->  
    <mvc:annotation-driven></mvc:annotation-driven>  
</beans> 

spring,xml

<?xml version="1.0" encoding="UTF-8"?>  
<beans  
    xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns:p="http://www.springframework.org/schema/p"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd  
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd  
    ">  
      
</beans>

校驗類

package cn.et;  
import javax.validation.constraints.Max;  
import javax.validation.constraints.Min;  
import javax.validation.constraints.Pattern;  
import javax.validation.constraints.Size;  
  
import org.hibernate.validator.constraints.NotEmpty;  
  
  
public class UserInfo {  
    /**  
     * NotNull 屬性名 !=null  
     * NotEmpty 屬性名!=null &&  !屬性名.equals("")  
     */  
    @NotEmpty(message="使用者名稱不能為空")  
    private String userName;  
      
    @NotEmpty(message="密碼不能為空")  
    private String password;  
      
    @NotEmpty(message="再次輸入不能為空")  
    private String repassword;  
      
    // [email protected]    
    @Pattern(message="郵箱格式錯誤",regexp="[email protected]+\\..+")  
    private String email;  
      
    @NotEmpty(message="年齡不能為空")  
    @Min(value=1,message="年齡必須大於1")  
    @Max(value=100,message="年齡必須小於100")  
    private String age;  
      
    @Size(min=11, max=11,message="手機號碼必須是11位")  
    private String phone;  
      
    @Pattern(message="時間格式錯誤",regexp="(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29)")  
    private String time;  
      
    @Pattern(message="網址格式錯誤",regexp="^([hH][tT]{2}[pP]:/*|[hH][tT]{2}[pP][sS]:/*|[fF][tT][pP]:/*)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\/])+(\\?{0,1}(([A-Za-z0-9-~]+\\={0,1})([A-Za-z0-9-~]*)\\&{0,1})*)$")  
    private String url;  
      
    public String getTime() {  
        return time;  
    }  
    public void setTime(String time) {  
        this.time = time;  
    }  
    public String getUrl() {  
        return url;  
    }  
    public void setUrl(String url) {  
        this.url = url;  
    }  
    public String getUserName() {  
        return userName;  
    }  
    public void setUserName(String userName) {  
        this.userName = userName;  
    }  
    public String getPassword() {  
        return password;  
    }  
    public void setPassword(String password) {  
        this.password = password;  
    }  
    public String getRepassword() {  
        return repassword;  
    }  
    public void setRepassword(String repassword) {  
        this.repassword = repassword;  
    }  
    public String getEmail() {  
        return email;  
    }  
    public void setEmail(String email) {  
        this.email = email;  
    }  
    public String getAge() {  
        return age;  
    }  
    public void setAge(String age) {  
        this.age = age;  
    }  
    public String getPhone() {  
        return phone;  
    }  
    public void setPhone(String phone) {  
        this.phone = phone;  
    }  
}  


持久層

package cn.et;  
import javax.validation.Valid;  
  
import org.springframework.stereotype.Controller;  
import org.springframework.validation.BindingResult;  
import org.springframework.validation.FieldError;  
import org.springframework.web.bind.annotation.ModelAttribute;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestMethod;  
/**  
 * 後臺驗證步驟  
 *  1.javabean新增驗證註解  
 *  2.action中使用@Valid表示javabean 使用Errors或者BindingResult判斷是否驗證失敗  
 *  3.出現jar包衝突4.3.2  
 *    
 * @author Administrator  
 *  
 */  
@Controller  
public class RegController {  
    @RequestMapping(value="/reg",method=RequestMethod.POST)  
    public String reg(@ModelAttribute("user") @Valid UserInfo user,BindingResult errors){  
        //用於判斷密碼是否一致  
        if(!user.getPassword().equals(user.getRepassword())){  
            errors.addError(new FieldError("userInfo","repassword","兩次密碼不一致"));  
        }  
        if(errors.hasErrors()){                                                                           
            return "/reg.jsp";  
        }  
        return "/suc.jsp";  
    }  
}  

reg.jsp顯示介面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>  
<%  
String path = request.getContextPath();  
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
%>  
  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
<html>  
  <head>  
    <base href="<%=basePath%>">  
      
    <title>My JSP 'MyJsp.jsp' starting page</title>  
      
    <meta http-equiv="pragma" content="no-cache">  
    <meta http-equiv="cache-control" content="no-cache">  
    <meta http-equiv="expires" content="0">      
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
    <meta http-equiv="description" content="This is my page">  
    <!-- 
    <link rel="stylesheet" type="text/css" href="styles.css"> 
    -->  
    <script type="text/javascript">  
        function checkSubmit(){  
            //獲取使用者名稱並判斷是否為空  
            var userName=document.getElementsByName("userName")[0].value;  
            if(userName==null || userName==""){  
                alert("使用者名稱不能為空");  
                return;  
            }  
            //獲取密碼並判斷是否為空  
            var password=document.getElementsByName("password")[0].value;  
            if(password==null || password==""){  
                alert("密碼不能為空");  
                return;  
            }  
            //獲取再次輸入的密碼並判斷是否為空  
            var repassword=document.getElementsByName("repassword")[0].value;  
            if(repassword==null || repassword==""){  
                alert("重複密碼不能為空");  
                return;  
            }  
            if(password!=repassword){  
                alert("兩次輸入密碼不一致");  
                return;  
            }  
            //提交  
            document.forms[0].submit();  
        }  
    </script>  
  </head>  
  
  <body>  
      <form action="<%=path%>/reg" method="post">  
            使用者名稱:<input type="text" name="userName" />  
            <!-- 將校驗訊息顯示出來(如果沒有錯誤就不顯示)-->  
            <font color="red"><form:errors path="user.userName"></form:errors></font>  
            <br/>  
            密碼:<input type="password" name="password" />  
            <font color="red"><form:errors path="user.password"></form:errors></font>  
            <br/>  
            重複密碼:<input type="password" name="repassword" />  
            <font color="red"><form:errors path="user.repassword"></form:errors></font>  
            <br/>  
            郵件:<input type="text" name="email" />  
            <font color="red"><form:errors path="user.email"></form:errors></font>  
            <br/>  
            年齡:<input type="text" name="age" />  
            <font color="red"><form:errors path="user.age"></form:errors></font>  
            <br/>  
            手機號碼:<input type="text" name="phone" />  
            <font color="red"><form:errors path="user.phone"></form:errors></font>  
            <br/>  
            <!-- 時間  輸入格式 yyyy-MM-dd -->  
            時間:<input type="text" name="time" >  
            <font color="red"><form:errors path="user.time"></form:errors></font>  
            <br/>  
            <!-- 網址 http://www.baidu.com http://ip:埠/ -->  
            個人網址:<input type="text" name="url" >  
            <font color="red"><form:errors path="user.url"></form:errors></font>  
            <br/>  
            <input type="button" value="提交" onclick="checkSubmit()">  
        </form>  
  </body>  
</html>