詳解SpringMVC學習系列(6) 之 數(shù)據(jù)驗證
在系列(4)、(5)中我們展示了如何綁定數(shù)據(jù),綁定完數(shù)據(jù)之后如何確保我們得到的數(shù)據(jù)的正確性?這就是我們本篇要說的內(nèi)容 —> 數(shù)據(jù)驗證。
這里我們采用Hibernate-validator來進行驗證,Hibernate-validator實現(xiàn)了JSR-303驗證框架支持注解風格的驗證。首先我們要到http://hibernate.org/validator/下載需要的jar包,這里以4.3.1.Final作為演示,解壓后把hibernate-validator-4.3.1.Final.jar、jboss-logging-3.1.0.jar、validation-api-1.0.0.GA.jar這三個包添加到項目中。
配置之前項目中的springservlet-config.xml文件,如下:
<!-- 默認的注解映射的支持 --> <mvc:annotation-driven validator="validator" conversion-service="conversion-service" /> <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> <property name="providerClass" value="org.hibernate.validator.HibernateValidator"/> <!--不設(shè)置則默認為classpath下的 ValidationMessages.properties --> <property name="validationMessageSource" ref="validatemessageSource"/> </bean> <bean id="conversion-service" class="org.springframework.format.support.FormattingConversionServiceFactoryBean" /> <bean id="validatemessageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basename" value="classpath:validatemessages"/> <property name="fileEncodings" value="utf-8"/> <property name="cacheSeconds" value="120"/> </bean>
其中<property name="basename" value="classpath:validatemessages"/>中的classpath:validatemessages為注解驗證消息所在的文件,需要我們在resources文件夾下添加。
在com.demo.web.controllers包中添加一個ValidateController.java內(nèi)容如下:
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 意思是在把數(shù)據(jù)綁定到@ModelAttribute("contentModel") 后就進行驗證。
在com.demo.web.models包中添加一個ValidateModel.java內(nèi)容如下:
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=150,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文件中添加以下內(nèi)容:
name.not.empty=\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A\u3002 age.not.inrange=\u5E74\u9F84\u8D85\u51FA\u8303\u56F4\u3002 email.not.correct=\u90AE\u7BB1\u5730\u5740\u4E0D\u6B63\u786E\u3002 email.not.empty=\u7535\u5B50\u90AE\u4EF6\u4E0D\u80FD\u60DF\u6050\u3002
其中name.not.empty等分別對應了ValidateModel.java文件中message=”xxx”中的xxx名稱,后面的內(nèi)容是在輸入中文是自動轉(zhuǎn)換的ASCII編碼,當然你也可以直接把xxx寫成提示內(nèi)容,而不用另建一個validatemessages.properties文件再添加,但這是不正確的做法,因為這樣硬編碼的話就沒有辦法進行國際化了。
在views文件夾中添加validatetest.jsp和validatesuccess.jsp兩個視圖,內(nèi)容分別如下:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form:form modelAttribute="contentModel" method="post"> <form:errors path="*"></form:errors><br/><br/> name:<form:input path="name" /><br/> <form:errors path="name"></form:errors><br/> age:<form:input path="age" /><br/> <form:errors path="age"></form:errors><br/> email:<form:input path="email" /><br/> <form:errors path="email"></form:errors><br/> <input type="submit" value="Submit" /> </form:form> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> 驗證成功! </body> </html>
其中特別要指出的是validatetest.jsp視圖中<form:form modelAttribute="contentModel" method="post">的modelAttribute="xxx"后面的名稱xxx必須與對應的@Valid @ModelAttribute("xxx") 中的xxx名稱一致,否則模型數(shù)據(jù)和錯誤信息都綁定不到。
<form:errors path="name"></form:errors>即會顯示模型對應屬性的錯誤信息,當path="*"時則顯示模型全部屬性的錯誤信息。
運行測試:
直接點擊提交:
可以看到正確顯示了設(shè)置的錯誤信息。
填寫錯誤數(shù)據(jù)提交:
可以看到依然正確顯示了設(shè)置的錯誤信息。
填寫正確數(shù)據(jù)提交:
可以看到驗證成功。
下面是主要的驗證注解及說明:
數(shù)據(jù)驗證的內(nèi)容到此結(jié)束,代碼下載:demo
更多信息請參考官方文檔:http://docs.jboss.org/hibernate/validator/4.3/reference/en-US/html/validator-usingvalidator.html
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
從Hello?World開始理解GraphQL背后處理及執(zhí)行過程
這篇文章主要為大家介紹了從Hello?World開始理解GraphQL背后處理過程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-08-08SpringBoot使用ExceptionHandler做異常處理
這篇文章主要介紹了SpringBoot使用ExceptionHandler做異常處理,這篇文章通過多種方法案例來介紹該項技術(shù)的使用,需要的朋友可以參考下2021-06-06Spring Security OAuth2 授權(quán)碼模式的實現(xiàn)
這篇文章主要介紹了Spring Security OAuth2 授權(quán)碼模式的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-08-08詳解Java中super的幾種用法并與this的區(qū)別
這篇文章主要介紹了Java中super的幾種用法并與this的區(qū)別,有需要的朋友可以參考一下2013-12-12java中的Io(input與output)操作總結(jié)(二)
這一節(jié)我們來討論關(guān)于文件自身的操作包括:創(chuàng)建文件對象、創(chuàng)建和刪除文件、文件的判斷和測試、創(chuàng)建目錄、獲取文件信息、列出文件系統(tǒng)的根目錄、列出目錄下的所有文件,等等,感興趣的朋友可以了解下2013-01-01