首頁 Java java教程 SpringMVC學習系列(6) 之 資料驗證

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

Mar 03, 2017 am 10:58 AM
springmvc

在系列(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

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

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

SpringBoot與SpringMVC的比較及差別分析 SpringBoot與SpringMVC的比較及差別分析 Dec 29, 2023 am 11:02 AM

SpringBoot和SpringMVC都是Java開發中常用的框架,但它們之間有一些明顯的差異。本文將探究這兩個框架的特點和用途,並對它們的差異進行比較。首先,我們來了解一下SpringBoot。 SpringBoot是由Pivotal團隊開發的,它旨在簡化基於Spring框架的應用程式的建立和部署。它提供了一種快速、輕量級的方式來建立獨立的、可執行

比較SpringBoot與SpringMVC的差異是什麼? 比較SpringBoot與SpringMVC的差異是什麼? Dec 29, 2023 am 10:46 AM

SpringBoot與SpringMVC的不同之處在哪裡? SpringBoot和SpringMVC是兩個非常流行的Java開發框架,用於建立Web應用程式。儘管它們經常分別被使用,但它們之間的差異也是很明顯的。首先,SpringBoot可以被看作是一個Spring框架的擴充或增強版。它旨在簡化Spring應用程式的初始化和配置過程,以幫助開發人

SpringBoot與SpringMVC的差別是什麼? SpringBoot與SpringMVC的差別是什麼? Dec 29, 2023 pm 05:19 PM

SpringBoot和SpringMVC是Java開發中常用的兩個框架,它們都是由Spring框架所提供的,但在功能和使用方式上有一些區別。本文將分別介紹SpringBoot和SpringMVC的特點和區別。一、SpringBoot的特點:簡化配置:SpringBoot透過約定優於配置的原則,大大簡化了專案的配置過程。它可以自動配置專案所需的參數,開發人

springboot和springmvc有哪些差別 springboot和springmvc有哪些差別 Jun 07, 2023 am 10:10 AM

springboot和springmvc區別是:1、意義不同;2、配置不同;3、依賴項不同;4、開發時間不同;5、生產力不同;6、實現JAR打包功能的方式不同;7、是否提供批次處理功能;8、作用不同;9、社群和文件支援不同;10、是否需要部署描述符。

spring和springmvc有哪些差別 spring和springmvc有哪些差別 Dec 29, 2023 pm 05:02 PM

spring和springmvc的區別:1、定位和功能;2、核心功能;3、應用領域;4、擴展性。詳細介紹:1、定位和功能,Spring是一個綜合性的應用程式開發框架,提供了依賴注入、面向切面編程、事務管理等功能,旨在簡化企業級應用程式的開發,而Spring MVC是Spring框架中的一個模組,用於Web應用程式的開發,實現了MVC模式;2、核心功能等等。

Java API 開發中使用 SpringMVC 進行 Web 服務處理 Java API 開發中使用 SpringMVC 進行 Web 服務處理 Jun 17, 2023 pm 11:38 PM

隨著網路的發展,Web服務越來越普遍。 JavaAPI作為一種應用程式接口,也不斷地推出新的版本來適應不同的應用場景。而SpringMVC作為一種流行的開源框架,能夠幫助我們輕鬆地建立Web應用程式。本文將詳細講解在JavaAPI開發中,如何使用SpringMVC進行Web服務處理,包括配置SpringMVC、編寫控制器、使用

Java的SpringMVC攔截器怎麼用 Java的SpringMVC攔截器怎麼用 May 13, 2023 pm 02:55 PM

攔截器(interceptor)的作用SpringMVC的攔截器類似於Servlet開發中的過濾器Filter,用於對處理器進行預處理和後處理。將攔截器依一定的順序聯結成一條鏈,這條鏈稱為攔截器鏈(InterceptorChain)。在存取被攔截的方法或欄位時,攔截器鏈中的攔截器就會依其先前定義的順序被呼叫。攔截器也是AOP思想的具體實作。攔截器和過濾器區別區別過濾器(Filter)攔截器(Intercepter)使用範圍是servlet規格中的一部分,任何JavaWeb工程都可以使用是Spri

比較SpringBoot和SpringMVC的異同點 比較SpringBoot和SpringMVC的異同點 Dec 29, 2023 am 08:30 AM

解析SpringBoot和SpringMVC之間的異同SpringBoot和SpringMVC是Java領域中非常重要的開發架構。雖然它們都屬於Spring框架的一部分,但在使用和功能上有一些明顯的區別。本文將對SpringBoot和SpringMVC進行比較,解析它們之間的異同。首先,讓我們來了解一下SpringBoot。 SpringBo

See all articles