SpringMVC實現Validation校驗過程詳解
阿新 • • 發佈:2020-01-07
這篇文章主要介紹了SpringMVC實現Validation校驗過程詳解,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
一、概述
對前端的校驗大多數通過js在頁面校驗,這種方法比較簡單,如果對安全性考慮,還要在後臺校驗。
springmvc使用JSR-303(javaEE6規範的一部分)校驗規範,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 配置
<!-- 校驗器 --> <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> <!-- 校驗器 --> <property name="providerClass" value="org.hibernate.validator.HibernateValidator" /> <!-- 指定校驗使用的資原始檔,如果不指定則預設使用classpath下的ValidationMessages.properties --> <property name="validationMessageSource" ref="messageSource" /> </bean> <!-- 校驗錯誤資訊配置檔案 --> <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" /> <!-- 對資原始檔內容快取時間,單位秒 --> <property name="cacheSeconds" value="120" /> </bean> <!-- 自定義webBinder --> <bean id="customBinder" class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer"> <!-- 使用converter進行引數轉 --> <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中注入自定義屬性編輯器、自定義轉換器 --> <property name="webBindingInitializer" ref="customBinder"></property> <!-- 加入 json資料的訊息轉換器 MappingJacksonHttpMessageConverter依賴Jackson的包 --> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean> </list> </property> </bean>
2.3 建立CustomValidationMessages
在classpath下建立CustomValidationMessages.properties
# 校驗提示資訊:還需要在java中配置 items.name.length.error=商品長度請限制在1-30之間items.createtime.is.notnull=請輸入商品生產日期
2.4 校驗規則
商品資訊提交時校驗 ,商品生產日期不能為空,商品名稱長度在1到30字元之間
public class Items { private Integer id; //商品名稱的長度請限制在1到30個字元 @Size(min=1,max=30,message="{items.name.length.error}") private String name; private Float price; private String pic; //請輸入商品生產日期 @NotNull(message="{items.createtime.is.notnull}") private Date createtime; private String detail; }
2.5 捕獲錯誤
需要修改controller方法,在要校驗的pojo前邊加上@Validated,
public String editItemSubmit(Model model,Integer id,@Validated @ModelAttribute(value="itemsCustom") ItemsCustom itemsCustom,BindingResult bindingResult,//上傳圖片 MultipartFile pictureFile )throws Exception{ //輸出校驗錯誤資訊 //如果引數繫結時有錯 //輸出校驗錯誤資訊 //如果引數繫結時有錯 if(bindingResult.hasErrors()){ //獲取錯誤 List<ObjectError> errors = bindingResult.getAllErrors(); //準備在頁面輸出errors,頁面使用jstl遍歷 model.addAttribute("errors",errors); for(ObjectError error:errors){ //輸出錯誤資訊 System.out.println(error.getDefaultMessage()); } //如果校驗錯誤,回到商品修改頁面 return "editItem"; } }
2.6 在頁面上展示錯誤
<!-- 錯誤資訊 --> <c:forEach items="${errors }" var="error"> ${error.defaultMessage }<br/> </c:forEach>
2.7 分組校驗
需求
針對不同的controller方法通過分組校驗達到個性化校驗的目的,修改商品修改功能,只校驗生產日期不能為空。
第一步:建立分組介面
public interface ValidGroup1 { //介面不定義方法,就是隻標識 哪些校驗 規則屬於該 ValidGroup1分組 }
第二步:定義校驗規則屬於哪個分組
//請輸入商品生產日期 //通過groups指定此校驗屬於哪個分組,可以指定多個分組 @NotNull(message="{items.createtime.is.notnull}",groups={ValidGroup1.class}) private Date createtime;
第三步:在controller方法定義使用校驗的分組
public String editItemSubmit(Model model,@Validated(value={ValidGroup1.class}) @ModelAttribute(value="itemsCustom") ItemsCustom itemsCustom,//上傳圖片 MultipartFile pictureFile )throws Exception{ //...其他程式碼省略... }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。