SpringMVC實(shí)現(xiàn)Validation校驗(yàn)過(guò)程詳解
這篇文章主要介紹了SpringMVC實(shí)現(xiàn)Validation校驗(yàn)過(guò)程詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
一、概述
對(duì)前端的校驗(yàn)大多數(shù)通過(guò)js在頁(yè)面校驗(yàn),這種方法比較簡(jiǎn)單,如果對(duì)安全性考慮,還要在后臺(tái)校驗(yàn)。
springmvc使用JSR-303(javaEE6規(guī)范的一部分)校驗(yàn)規(guī)范,springmvc使用的是Hibernate Validator(和Hibernate的ORM)
二、步驟
2.1 引入 Hibernate Validator
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.4.1.Final</version> </dependency>
2.2 配置
<!-- 校驗(yàn)器 -->
<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<!-- 校驗(yàn)器 -->
<property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
<!-- 指定校驗(yàn)使用的資源文件,如果不指定則默認(rèn)使用classpath下的ValidationMessages.properties -->
<property name="validationMessageSource" ref="messageSource" />
</bean>
<!-- 校驗(yàn)錯(cuò)誤信息配置文件 -->
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<!-- 資源文件名 -->
<property name="basenames">
<list>
<value>classpath:CustomValidationMessages</value>
</list>
</property>
<!-- 資源文件編碼格式 -->
<property name="fileEncodings" value="utf-8" />
<!-- 對(duì)資源文件內(nèi)容緩存時(shí)間,單位秒 -->
<property name="cacheSeconds" value="120" />
</bean>
<!-- 自定義webBinder -->
<bean id="customBinder"
class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<!-- 使用converter進(jìn)行參數(shù)轉(zhuǎn) -->
<property name="conversionService" ref="conversionService" />
<!-- 配置validator -->
<property name="validator" ref="validator" />
<!-- propertyEditorRegistrars用于屬性編輯器 -->
<!-- <property name="propertyEditorRegistrars"> <list> <ref bean="customPropertyEditor"
/> </list> </property> -->
</bean>
<!-- 注解適配器 -->
<bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<!-- 在webBindingInitializer中注入自定義屬性編輯器、自定義轉(zhuǎn)換器 -->
<property name="webBindingInitializer" ref="customBinder"></property>
<!-- 加入 json數(shù)據(jù)的消息轉(zhuǎn)換器 MappingJacksonHttpMessageConverter依賴Jackson的包 -->
<property name="messageConverters">
<list>
<bean
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
</list>
</property>
</bean>
2.3 創(chuàng)建CustomValidationMessages
在classpath下創(chuàng)建CustomValidationMessages.properties
# 校驗(yàn)提示信息:還需要在java中配置 items.name.length.error=商品長(zhǎng)度請(qǐng)限制在1-30之間items.createtime.is.notnull=請(qǐng)輸入商品生產(chǎn)日期
2.4 校驗(yàn)規(guī)則
商品信息提交時(shí)校驗(yàn) ,商品生產(chǎn)日期不能為空,商品名稱長(zhǎng)度在1到30字符之間
public class Items {
private Integer id;
//商品名稱的長(zhǎng)度請(qǐng)限制在1到30個(gè)字符
@Size(min=1,max=30,message="{items.name.length.error}")
private String name;
private Float price;
private String pic;
//請(qǐng)輸入商品生產(chǎn)日期
@NotNull(message="{items.createtime.is.notnull}")
private Date createtime;
private String detail;
}
2.5 捕獲錯(cuò)誤
需要修改controller方法,在要校驗(yàn)的pojo前邊加上@Validated,
public String editItemSubmit(Model model,Integer id,
@Validated @ModelAttribute(value="itemsCustom") ItemsCustom itemsCustom,
BindingResult bindingResult,
//上傳圖片
MultipartFile pictureFile
)throws Exception{
//輸出校驗(yàn)錯(cuò)誤信息
//如果參數(shù)綁定時(shí)有錯(cuò)
//輸出校驗(yàn)錯(cuò)誤信息
//如果參數(shù)綁定時(shí)有錯(cuò)
if(bindingResult.hasErrors()){
//獲取錯(cuò)誤
List<ObjectError> errors = bindingResult.getAllErrors();
//準(zhǔn)備在頁(yè)面輸出errors,頁(yè)面使用jstl遍歷
model.addAttribute("errors", errors);
for(ObjectError error:errors){
//輸出錯(cuò)誤信息
System.out.println(error.getDefaultMessage());
}
//如果校驗(yàn)錯(cuò)誤,回到商品修改頁(yè)面
return "editItem";
}
}
2.6 在頁(yè)面上展示錯(cuò)誤
<!-- 錯(cuò)誤信息 -->
<c:forEach items="${errors }" var="error">
${error.defaultMessage }<br/>
</c:forEach>
2.7 分組校驗(yàn)
需求
針對(duì)不同的controller方法通過(guò)分組校驗(yàn)達(dá)到個(gè)性化校驗(yàn)的目的,修改商品修改功能,只校驗(yàn)生產(chǎn)日期不能為空。
第一步:創(chuàng)建分組接口
public interface ValidGroup1 {
//接口不定義方法,就是只標(biāo)識(shí) 哪些校驗(yàn) 規(guī)則屬于該 ValidGroup1分組
}
第二步:定義校驗(yàn)規(guī)則屬于哪個(gè)分組
//請(qǐng)輸入商品生產(chǎn)日期
//通過(guò)groups指定此校驗(yàn)屬于哪個(gè)分組,可以指定多個(gè)分組 @NotNull(message="{items.createtime.is.notnull}",groups={ValidGroup1.class})
private Date createtime;
第三步:在controller方法定義使用校驗(yàn)的分組
public String editItemSubmit(Model model,Integer id,
@Validated(value={ValidGroup1.class}) @ModelAttribute(value="itemsCustom") ItemsCustom itemsCustom,
BindingResult bindingResult,
//上傳圖片
MultipartFile pictureFile
)throws Exception{
//...其他代碼省略...
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
解決springboot報(bào)錯(cuò)找不到自動(dòng)注入的service問(wèn)題
這篇文章主要介紹了解決springboot報(bào)錯(cuò)找不到自動(dòng)注入的service問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08
Yml轉(zhuǎn)properties文件工具類(lèi)YmlUtils的詳細(xì)過(guò)程(不用引任何插件和依賴)
這篇文章主要介紹了Yml轉(zhuǎn)properties文件工具類(lèi)YmlUtils(不用引任何插件和依賴),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-08-08
SpringBoot整合JDBC的實(shí)現(xiàn)
這篇文章主要介紹了SpringBoot整合JDBC的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
java并發(fā)編程之深入理解Synchronized的使用
文詳細(xì)講述了線程、進(jìn)程的關(guān)系及在操作系統(tǒng)中的表現(xiàn),這是多線程學(xué)習(xí)必須了解的基礎(chǔ)。本文將接著講一下Java線程同步中的一個(gè)重要的概念synchronized,希望能夠給你有所幫助2021-06-06
Spring boot 默認(rèn)靜態(tài)資源路徑與手動(dòng)配置訪問(wèn)路徑的方法
這篇文章主要介紹了Spring boot 默認(rèn)靜態(tài)資源路徑與手動(dòng)配置訪問(wèn)路徑的方法,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2017-05-05
mybatis的insert插入后獲取自增id的方法詳解(從controller到mapper)
這篇文章主要介紹了mybatis的insert插入后獲取自增id的示例代碼,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-10-10
淺談Springboot實(shí)現(xiàn)攔截器的兩種方式
本文詳細(xì)的介紹了Springboot攔截器的兩種方式實(shí)現(xiàn),一種就是用攔截器,一種就是過(guò)濾器,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-08-08
詳解Java如何在CompletableFuture中實(shí)現(xiàn)日志記錄
這篇文章主要為大家詳細(xì)介紹了一種slf4j自帶的MDC類(lèi),來(lái)記錄完整的請(qǐng)求日志,和在CompletableFuture異步線程中如何保留鏈路id,需要的可以參考一下2023-04-04

