Springmvc_validation 效驗器


springmvc-validation效驗器的使用介紹

  對於任何一個應用來說,都會做數據的有效性效驗,但是只在前端做並不是很安全,考慮到安全性這個時候會要求我們在服務端也對數據進行有效驗證,springmvc自身對數據在服務端有一個比較好的支持,springmvc能將我們前台提交的數據按照我們事先定下的規則,進行效驗判斷,對於不合格的數據信息,springmvc會把他保存到一個BindingResult 的類里面,這里面存放是錯誤集合,從而言之就可以把這些錯誤信息輸出到jsp頁面。

使用validation接口進行驗證:

    在我們注解驅動中注入validation 效驗器<mvc:annotation-driven conversion-service="conversionService" validator="validator"/> 

所需依賴的jar包:

   

springmvc配置參考:

  這里我們指定了資源文件,以及一些常用配置,往后錯誤消息配置到CustomValidationMessage.properties 中以key value 形式讀取

 1 <!--hibernate-validator 效驗器 
 2         org.springframework.validation.beanvalidation.LocalValidatorFactoryBean 這個是spring-context 提供的效驗的接口
 3     -->
 4     <bean id = "validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
 5         <!-- hibernate的效驗器 -->
 6             <property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
 7         <!-- 加載資源文件,在指定文件中配置錯誤信息如果不加載默認會去找classpath下的ValidationMessage.properties -->
 8             <property name="validationMessageSource" ref ="messageSource"></property>
 9     </bean>
10     <bean id = "messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
11         <!-- 加載資源文件名
12             basenames:不用加properties
13     --> 
14         <property name="basenames">
15             <list>
16                 <value>classpath:CustomValidationMessage</value>
17             </list>
18         </property>
19         <!-- 資源文件的編碼格式 -->
20         <property name="defaultEncoding" value="UTF-8"/>
21         <!-- 加載超時 120 秒 重新加載-->
22         <property name="cacheSeconds" value="120"/> 
23     </bean>

我們實體類pojo 的參考:

 1     //效驗名稱在1 到 10 字符之間 不建議在里面直接寫message 建議寫在配置文件里面以國際化方式去讀取錯誤信息
 2     @Size(min=2,max=10,message="{items.name.length.error}")
 3     @NotNull(message="{items.name.isNull}")
 4     private String name;
 5     //非空的效驗
 6     @NotNull(message="{items.createtime.isNull}")
 7     private Date createtime;
 8     
 9     @NotNull(message="{items.detail.isNull}")
10     private String detail;

controller代碼參考:

  在你需要效驗的pojo前面添加@Validated 表示這是需要效驗,在pojo 后面添加BindingResult 來接受它效驗的錯誤信息

  注意:@Validated 和BindingResult 是配對出現,一前一后方式,這本案例中只是簡單實現了這個功能,但並不是完整的。

 1 /**
 2      *     商品信息提交的方法
 3      * @return   重定向的使用
 4      * @throws Exception
 5      * @Validated: 注解效驗器
 6      * BindingResult:接受錯誤信息 9      */
10     @RequestMapping("/editItemsSubmit")
11     public String editItemsSubmit(Model model, Integer id,@Validated ItemsCustom itemsCustom ,BindingResult bindingResult)throws Exception{
12         if (bindingResult.hasErrors()) {
13             List<ObjectError> itemsErrorList = bindingResult.getAllErrors();
14             for(ObjectError objectError:itemsErrorList){
15                 System.out.println(objectError.getDefaultMessage());
16             }    
17             model.addAttribute("itemsErrorList", itemsErrorList);
18             return "items/editItems";
19         }
20         // 調用service 里面的接口方法 
21         itemsService.updateItems(id, itemsCustom);
22         // 使用重定向到
23         //    queryitems.do return "redirect:queryItems.do"; 
24         //使用forward  可以在其他頁面獲取值 對象等
25         //return "forward:queryItems.do"; 
26         return "success"; 
27     }

頁面參JSP考代碼:

  測試代碼打印出錯誤消息

1     <c:if test="${itemsErrorList != null }">
2         <c:forEach items="${itemsErrorList }" var="error" varStatus="index">
3             ${error.defaultMessage}
4         </c:forEach>
5     </c:if>

在資源文件中配置錯誤信息CustomValidationMessage.properties:

1 # 配置效驗器的錯誤信息,key value 形式
2                         # items 的錯誤配置
3 items.name.length.error=請輸入2到10個字符的商品名稱!
4 items.name.isNull=商品名稱不能為空!
5 items.createtime.isNull=請輸入商品的生產日期!
6 items.detail.isNull=商品描述不能為空!

Validation 效驗常用限制注解:

  @Null:限制只能為null

  @NotNull:限制必須不能為空

  @AssertFalse 限制必須為false

  @AssertTrue 限制必須為true

  @DecimalMax(value) 限制必須為一個不大於指定值得數字

  @DecimalMax(value)限制必須為一個不小於指定值得數字

  @Digits(integer,fraction)限制必須為一個小數,且整數部分的位數不能超過integer,小數部分不能超過fraction

  @Futrue 限制必須為一個將來的日期

  @Max(value) 限制必須為一個不大於指定值得數字

  @Min(value)限制必須為一個不小於指定值得數字

  @Past限制必須為一個過去的時間

  @Pattern(value)限制為符合指定的正則表達式

  @Size(max,min)限制字符長度在min 到 max 之間


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM