搜尋
首頁Javajava教程SpringMVC學習系列(6) 之 資料驗證

在系列(SpringMVC學習系列(6) 之 資料驗證)、(SpringMVC學習系列(6) 之 資料驗證)中我們展示如何綁定數據,綁定完數據之後如何確保我們得到的數據的正確性?這就是我們本篇要說的 —> 資料驗證。

這裡我們採用Hibernate-validator來進行驗證,Hibernate-validator實作了JSR-SpringMVC學習系列(6) 之 資料驗證0SpringMVC學習系列(6) 之 資料驗證驗證框架支援註解風格的驗證。首先我們要到http://www.php.cn/下載所需的jar包,這裡以SpringMVC學習系列(6) 之 資料驗證.SpringMVC學習系列(6) 之 資料驗證.SpringMVC學習系列(6) 之 資料驗證.Final作為演示,解壓縮後把hibernate-validator-SpringMVC學習系列(6) 之 資料驗證.SpringMVC學習系列(6) 之 資料驗證.SpringMVC學習系列(6) 之 資料驗證.Final.jar、jboss-logging-SpringMVC學習系列(6) 之 資料驗證.SpringMVC學習系列(6) 之 資料驗證 .0.jar、validation-api-SpringMVC學習系列(6) 之 資料驗證.0.0.GA.jar這三個套件加入到專案中。

配置先前專案中的springservlet-config.xml文件,如下:

<!-- 默认的注解映射的支持 -->  
    <annotation-driven></annotation-driven>
    
    <bean>
        <property></property>
        <!--不设置则默认为classpath下的 ValidationMessages.properties -->
        <property></property>
    </bean>
    <bean></bean>
    <bean>  
        <property></property>  
        <property></property>  
        <property></property>  
    </bean>


其中property name="basename" value#="classpath:validatemessages"/>中的classpath:validatemessages為註解驗證訊息所在的文件,需要我們在resources資料夾下新增。

在com.demo.web.controllers套件中新增一個ValidateController.java內容如下:

package com.demo.web.controllers;import java.security.NoSuchAlgorithmException;import javax.validation.Valid;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.validation.BindingResult;import org.springframework.web.bind.annotation.ModelAttribute;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import com.demo.web.models.ValidateModel;

@Controller
@RequestMapping(value = "/validate")public class ValidateController {
    
    @RequestMapping(value="/test", method = {RequestMethod.GET})    public String test(Model model){        if(!model.containsAttribute("contentModel")){
            model.addAttribute("contentModel", new ValidateModel());
        }        return "validatetest";
    }
    
    @RequestMapping(value="/test", method = {RequestMethod.POST})    public String test(Model model, @Valid @ModelAttribute("contentModel") ValidateModel validateModel, BindingResult result) throws NoSuchAlgorithmException{        
        //如果有验证错误 返回到form页面
        if(result.hasErrors())            return test(model);        return "validatesuccess";     
    }
    
}


其中@Valid @ModelAttribute("contentModel") ValidateModel validateModel的@Valid 意思是把資料綁定到@ModelAttribute("contentModel") 後就進行驗證。

在com.demo.web.models套件中加入一個ValidateModel.java內容如下:

package com.demo.web.models;import org.hibernate.validator.constraints.Email;import org.hibernate.validator.constraints.NotEmpty;import org.hibernate.validator.constraints.Range;public class ValidateModel{
    
    @NotEmpty(message="{name.not.empty}")    private String name;
    @Range(min=0, max=SpringMVC學習系列(6) 之 資料驗證SpringMVC學習系列(6) 之 資料驗證0,message="{age.not.inrange}")    private String age;
    @NotEmpty(message="{email.not.empty}")
    @Email(message="{email.not.correct}")    private String email;    
    public void setName(String name){        this.name=name;
    }    public void setAge(String age){        this.age=age;
    }    public void setEmail(String email){        this.email=email;
    }    
    public String getName(){        return this.name;
    }    public String getAge(){        return this.age;
    }    public String getEmail(){        return this.email;
    }
    
}


在註解驗證訊息所在的檔案即validatemessages. properties檔案中加入以下內容:

name.not.empty=\uSpringMVC學習系列(6) 之 資料驗證SpringMVC學習系列(6) 之 資料驗證0D\u79F0\uSpringMVC學習系列(6) 之 資料驗證E0D\u80FD\uSpringMVC學習系列(6) 之 資料驗證ESpringMVC學習系列(6) 之 資料驗證A\u7A7A\uSpringMVC學習系列(6) 之 資料驗證00SpringMVC學習系列(6) 之 資料驗證
age.not.inrange=\uSpringMVC學習系列(6) 之 資料驗證E7SpringMVC學習系列(6) 之 資料驗證\u9F8SpringMVC學習系列(6) 之 資料驗證\u8D8SpringMVC學習系列(6) 之 資料驗證\uSpringMVC學習系列(6) 之 資料驗證SpringMVC學習系列(6) 之 資料驗證FA\u8SpringMVC學習系列(6) 之 資料驗證0SpringMVC學習系列(6) 之 資料驗證\uSpringMVC學習系列(6) 之 資料驗證6FSpringMVC學習系列(6) 之 資料驗證\uSpringMVC學習系列(6) 之 資料驗證00SpringMVC學習系列(6) 之 資料驗證
email.not.correct=\u90AE\u7BBSpringMVC學習系列(6) 之 資料驗證\uSpringMVC學習系列(6) 之 資料驗證7SpringMVC學習系列(6) 之 資料驗證0\uSpringMVC學習系列(6) 之 資料驗證7SpringMVC學習系列(6) 之 資料驗證0\uSpringMVC學習系列(6) 之 資料驗證E0D\u6B6SpringMVC學習系列(6) 之 資料驗證\u786E\uSpringMVC學習系列(6) 之 資料驗證00SpringMVC學習系列(6) 之 資料驗證
email.not.empty=\u7SpringMVC學習系列(6) 之 資料驗證SpringMVC學習系列(6) 之 資料驗證SpringMVC學習系列(6) 之 資料驗證\uSpringMVC學習系列(6) 之 資料驗證BSpringMVC學習系列(6) 之 資料驗證0\u90AE\uSpringMVC學習系列(6) 之 資料驗證EF6\uSpringMVC學習系列(6) 之 資料驗證E0D\u80FD\u60DF\u60SpringMVC學習系列(6) 之 資料驗證0\uSpringMVC學習系列(6) 之 資料驗證00SpringMVC學習系列(6) 之 資料驗證


其中name.not.empty等分別對應了ValidateModel.java檔案中message=”xxx」中的xxx名稱,後面的內容是在輸入中文是自動轉換的ASCII編碼,當然你也可以直接把xxx寫成提示內容,而不用另建一個validatemessages.properties檔案再添加,但這是不正確的做法,因為這樣硬編碼的話就沒有辦法進行國際化了。

在views資料夾中加入validatetest.jsp和validatesuccess.jsp兩個視圖,內容分別如下:

nbsp;html PUBLIC "-//WSpringMVC學習系列(6) 之 資料驗證C//DTD HTML SpringMVC學習系列(6) 之 資料驗證.0SpringMVC學習系列(6) 之 資料驗證 Transitional//EN" "http://www.wSpringMVC學習系列(6) 之 資料驗證.org/TR/htmlSpringMVC學習系列(6) 之 資料驗證/loose.dtd"><meta><title>Insert title here</title>
    <form>     
        
        <errors></errors><br><br>
            
        name:<input><br>
        <errors></errors><br>
        
        age:<input><br>
        <errors></errors><br>
        
        email:<input><br>
        <errors></errors><br>

        <input>
        
    </form>  


nbsp;html PUBLIC "-//WSpringMVC學習系列(6) 之 資料驗證C//DTD HTML SpringMVC學習系列(6) 之 資料驗證.0SpringMVC學習系列(6) 之 資料驗證 Transitional//EN" "http://www.wSpringMVC學習系列(6) 之 資料驗證.org/TR/htmlSpringMVC學習系列(6) 之 資料驗證/loose.dtd"><meta><title>Insert title here</title>
    验证成功!


其中特別要指出的是validatetest.jsp視圖中form:form modelAttribute##="contentModel" method="post">modelAttribute="xxx"#​​##後面的名稱xxx必須與對應的@Valid @ModelAttribute("xxx") 中的xxx名稱一致,否則模型資料和錯誤訊息都綁定不到。

form:errors path#="name">form:errors>即會顯示模型對應屬性的錯誤訊息,當path="*"時則顯示模型全部屬性的錯誤訊息.

執行測試:

SpringMVC學習系列(6) 之 資料驗證

直接點選提交:

SpringMVC學習系列(6) 之 資料驗證

可以看到正確顯示了設定的錯誤訊息。

填入錯誤資料提交:

SpringMVC學習系列(6) 之 資料驗證

可以看到依然正確顯示了設定的錯誤訊息。

填入正確資料提交:

SpringMVC學習系列(6) 之 資料驗證

SpringMVC學習系列(6) 之 資料驗證

可以看到驗證成功。

 

以下是主要的驗證註解及說明:

@DecimalMin(value=x)驗證註解的元素值小於等於@ DecimalMin指定的value值BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence.java.util .Date, java.util.Calendar; Additionally supported by HV, if theJoda Time date/time API is on the class path: any implementations ofReadablePartial andReadableInstant.驗證註解的元素值與指定的正規表示式匹配#驗證註解的元素值的在min和max(包含)指定區間之內,如字元長度、集合大小 #驗證註解的元素值不為空(不為null、去除首位空格後長度為0),不同於@NotEmpty,@NotBlank只應用於字串且在比較時會去除字串的空格

##註解

適用的資料型別

說明

@AssertFalse

Boolean, boolean

驗證註解的元素值是false

@AssertTrue

Boolean, boolean

#驗證註解的元素值是true

#@DecimalMax(value=x)

BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence.

驗證註解的元素值小於等於@ DecimalMax指定的value值

BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence.

#驗證註解的元素值小於等於@ DecimalMin指定的value值

# 驗證註解的元素值小於等於@ DecimalMin指定的value值

#@Digits(integer=整數位數, fraction=小數位數)

#的整數位數和小數位數上限

#@Future

#驗證註解的元素值(日期類型)比目前時間晚

############################################################ ######@Max(value=x)###############BigDecimal, BigInteger, byte, short,int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type ofCharSequence (the numeric value represented by the character sequence is evaluated), any sub-type of Number.############驗證註解的元素值小於等於@Max指定的value值############## #######@Min(value=x)#######

BigDecimal, BigInteger, byte, short,int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of CharSequence (the numeric value represented by the charse quence evaluated), any sub-type of Number.

驗證註解的元素值大於等於@Min指定的value值

@NotNull

Any type

#驗證註解的元素值不是null

@Null

#Any type

驗證註解的元素值是null

@Past

java.util.Date, java.util .Calendar; Additionally supported by HV, if theJoda Time date/time API is on the class path: any implementations ofReadablePartial andReadableInstant.

#驗證註解的元素值(日期類型)比目前時間早

#@Pattern(regex=正規表示式, flag=)

String. Additionally supported by HV: any sub-type of CharSequence.

#@Size(min=最小值, max=最大值)

String, Collection, Map and arrays. Additionally supported by HV: any sub-type of CharSequence.

@Valid

#########Any non-primitive type(引用類型)############驗證關聯的對象,如帳戶物件裡有一個訂單對象,指定驗證訂單物件#####################@NotEmpty##################CharSequence###,# ##Collection###, ###Map and Arrays#######

驗證註解的元素值不為null且不為空(字串長度不為0、集合大小不為0)

@Range(min=最小值, max=最大值)

#CharSequence, Collection, Map and Arrays,BigDecimal, BigInteger, CharSequence , byte, short, int, long and the respective wrappers of the primitive types

##驗證註解的元素值在最小值和最大值之間

@NotBlank

#CharSequence

@Length(min=下限, max=上限)

CharSequence##### ###########驗證註解的元素值長度在min和max區間內#####################@Email#### ##############CharSequence################驗證註解的元素值是Email,也可以透過正規表示式和flag指定自訂的email格式###############

 

更多資訊請參考官方文件:http://docs.jboss.org/hibernate/validator/SpringMVC學習系列(6) 之 資料驗證.SpringMVC學習系列(6) 之 資料驗證/reference/en-US/html/validator-usingvalidator.html

註: 之前沒注意前SpringMVC學習系列(6) 之 資料驗證SpringMVC學習系列(6) 之 資料驗證篇的範例程式碼,不知道為什麼當時打包上傳上去的是沒有.project專案檔的,導致下載後不能直接導入eclipse運行,虛擬機又被我刪掉了,這些範例程式碼也沒有備份,但是程式碼檔案還在的,所以可以新建一個Dynamic Web Project把對應的設定檔和controller還有view匯入就可以了,給大家造成的不便說聲抱歉。

以上就是SpringMVC學習系列(6) 之資料驗證的內容,更多相關內容請關注PHP中文網(www. php.cn)!


#

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
如何將Maven或Gradle用於高級Java項目管理,構建自動化和依賴性解決方案?如何將Maven或Gradle用於高級Java項目管理,構建自動化和依賴性解決方案?Mar 17, 2025 pm 05:46 PM

本文討論了使用Maven和Gradle進行Java項目管理,構建自動化和依賴性解決方案,以比較其方法和優化策略。

如何使用適當的版本控制和依賴項管理創建和使用自定義Java庫(JAR文件)?如何使用適當的版本控制和依賴項管理創建和使用自定義Java庫(JAR文件)?Mar 17, 2025 pm 05:45 PM

本文使用Maven和Gradle之類的工具討論了具有適當的版本控制和依賴關係管理的自定義Java庫(JAR文件)的創建和使用。

如何使用咖啡因或Guava Cache等庫在Java應用程序中實現多層緩存?如何使用咖啡因或Guava Cache等庫在Java應用程序中實現多層緩存?Mar 17, 2025 pm 05:44 PM

本文討論了使用咖啡因和Guava緩存在Java中實施多層緩存以提高應用程序性能。它涵蓋設置,集成和績效優勢,以及配置和驅逐政策管理最佳PRA

如何將JPA(Java持久性API)用於具有高級功能(例如緩存和懶惰加載)的對象相關映射?如何將JPA(Java持久性API)用於具有高級功能(例如緩存和懶惰加載)的對象相關映射?Mar 17, 2025 pm 05:43 PM

本文討論了使用JPA進行對象相關映射,並具有高級功能,例如緩存和懶惰加載。它涵蓋了設置,實體映射和優化性能的最佳實踐,同時突出潛在的陷阱。[159個字符]

Java的類負載機制如何起作用,包括不同的類載荷及其委託模型?Java的類負載機制如何起作用,包括不同的類載荷及其委託模型?Mar 17, 2025 pm 05:35 PM

Java的類上載涉及使用帶有引導,擴展程序和應用程序類負載器的分層系統加載,鏈接和初始化類。父代授權模型確保首先加載核心類別,從而影響自定義類LOA

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
4 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版