SpringMVC框架07——服務器端JSR303數據校驗

一、數據校驗概述

數據校驗分爲客戶端校驗和服務器端校驗,客戶端主要是經過過濾正經常使用戶的誤操做,是第一道防線,通常使用JavaScript代碼實現。可是隻有客戶端校驗是不夠的,攻擊者能夠繞過客戶端驗證直接進行非法輸入,這樣可能會引發系統異常,爲了確保數據的合法性,防止用戶經過非正常手段提交錯誤信息,必須加上服務器端驗證。
服務器端校驗是整個應用阻止非法數據的最後一道防線,經過應用中的編程實現。服務器端驗證對於系統的安全性、完整性、健壯性起到了相當重要的做用。在Spring MVC 框架中能夠利用Spring自帶的驗證框架驗證數據,也能夠利用JSR303實現數據驗證。
在Spring MVC 框架中有兩種方法能夠驗證輸入數據,一種是利用Spring自帶的驗證框架,另外一種是利用JSR303實現驗證,推薦使用JSR303驗證。html

二、JSR303驗證

對於JSR303驗證,目前有兩個實現,一個是Hibernate Validator,一個是Apache BVal。本教程採用的是Hibernate Validator,它和Hibernate無關,只是使用它進行數據驗證。java

(1)下載與安裝Hibernate Validator(maven項目忽略此步)

下載地址:https://sourceforge.net/projects/hibernate/files/hibernate-validator/
本教程使用的是hibernate-validator-5.4.0.Final-dist.zip
分別導入如下jar包:
dist目錄下的 hibernate-validator-t.4.0.Final.jargit

dist/lib/required目錄下的 classmate-1.3.1.jar、javax.el-3.0.1-b08.jar、jboss-logging-3.3.0.Final.jar、validation-api-1.1.0.Final.jarweb

(2)maven項目配置

在pom.xml中引入正則表達式

<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-validator</artifactId>
  <version>5.4.0.Final</version>
</dependency>

(3)註冊校驗器

在springmvc.xml配置文件中,註冊校驗器spring

<?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: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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
    
    <!--將AnnotationHandler自動掃描到IOC容器中-->
    <context:component-scan base-package="com.springmvc"></context:component-scan>

    <!--配置視圖解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--配置前綴-->
        <property name="prefix" value="/"></property>
        <!--配置後綴-->
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!--註冊校驗器-->
    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        <property name="providerClass" value="org.hibernate.validator.HibernateValidator"></property>
    </bean>
    <!--開啓Valid功能-->
    <mvc:annotation-driven validator="validator"></mvc:annotation-driven>

</beans>

(4)建立POJO實體類

import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.NotEmpty; import javax.validation.constraints.Pattern; public class User {
@NotEmpty(message
= "用戶名不能爲空") @Length(min = 6,max = 12,message = "用戶名的長度爲{min}-{max}位") private String username;
@NotEmpty(message
= "密碼不能爲空") @Length(min = 6,max = 8,message = "密碼的長度爲{min}-{max}位") private String password;
@NotEmpty(message
= "手機號不能爲空") @Pattern(regexp = "^1[34578]\\d{9}$",message = "手機號格式不正確") private String phone; //getter和setter方法 }

(5)建立控制器類

@Controller public class ValidatorTestController { @RequestMapping("/userLogin") public String login(@Valid User user, BindingResult br, Model model){ int errorCount = br.getErrorCount(); if(errorCount>0){ FieldError username = br.getFieldError("username"); FieldError password = br.getFieldError("password"); FieldError phone = br.getFieldError("phone"); if (username!=null) { model.addAttribute("userNameMSG",username.getDefaultMessage()); } if (password!=null) { model.addAttribute("pwdMSG",password.getDefaultMessage()); } if (phone!=null) { model.addAttribute("phoneMSG",phone.getDefaultMessage()); } return "testValidator"; } return "success"; } }

(6)建立數據校驗頁面

建立testValid.jsp頁面編程

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>數據校驗</title>
    <style> span{ color: red;}
    </style>
</head>
<body>

<form action="${pageContext.request.contextPath}/userLoginDemo" method="post">
    <p> 用戶名:<input type="text" name="username" value="${user.username}">
        <span>${userNameMSG}</span>
    </p>
    <p> 密碼:<input type="password" name="password" value="${user.password}">
        <span>${pwdMSG}</span>
    </p>
    <p> 手機號:<input type="text" name="phone" value="${user.phone}">
        <span>${phoneMSG}</span>
    </p>
    <p>
        <input type="submit" value="提交">
    </p>
</form>

</body>
</html>

  效果展現:api

三、JSR303經常使用標註類型

(1)空檢查

  • @Null 驗證對象是否爲null
  • @NotNull 驗證對象是否不爲null, 沒法查檢長度爲0的字符串
  • @NotBlank 檢查約束字符串是否是Null還有被Trim的長度是否大於0,只對字符串,且會去掉先後空格.
  • @NotEmpty 檢查約束元素是否爲NULL或者是EMPTY.

(2)Booelan檢查

  • @AssertTrue 驗證 Boolean 對象是否爲 true
  • @AssertFalse 驗證 Boolean 對象是否爲 false

(3)長度檢查

  • @Size(min=, max=) 驗證對象(Array,Collection,Map,String)長度是否在給定的範圍以內
  • @Length(min=, max=) Validates that the annotated string is between min and max included.

(4)日期檢查

  • @Past 驗證 Date 和 Calendar 對象是否在當前時間以前
  • @Future 驗證 Date 和 Calendar 對象是否在當前時間以後
  • @Pattern 驗證 String 對象是否符合正則表達式的規則

(5)數值檢查

建議使用在Stirng,Integer類型,不建議使用在int類型上,由於表單值爲「」時沒法轉換爲int,但能夠轉換爲Stirng爲"",Integer爲null數組

  • @Min 驗證 Number 和 String 對象是否大等於指定的值
  • @Max 驗證 Number 和 String 對象是否小等於指定的值
  • @DecimalMax 被標註的值必須不大於約束中指定的最大值. 這個約束的參數是一個經過BigDecimal定義的最大值的字符串表示.小數存在精度
  • @DecimalMin 被標註的值必須不小於約束中指定的最小值. 這個約束的參數是一個經過BigDecimal定義的最小值的字符串表示.小數存在精度
  • @Digits 驗證 Number 和 String 的構成是否合法
  • @Digits(integer=,fraction=) 驗證字符串是不是符合指定格式的數字,interger指定整數精度,fraction指定小數精度。
  • @Range(min=, max=) 檢查數字是否介於min和max之間.
  • @Range(min=10000,max=50000,message="range.bean.wage")
  • private BigDecimal wage;
  • @Valid 遞歸的對關聯對象進行校驗, 若是關聯對象是個集合或者數組,那麼對其中的元素進行遞歸校驗,若是是一個map,則對其中的值部分進行校驗.(是否進行遞歸驗證)
  • @CreditCardNumber信用卡驗證
  • @Email 驗證是不是郵件地址,若是爲null,不進行驗證,算經過驗證。
  • @ScriptAssert(lang= ,script=, alias=)
  • @URL(protocol=,host=, port=,regexp=, flags=)
相關文章
相關標籤/搜索