spring-springmvc-mybatis整合筆記(9)——validation校驗

一 何爲Validation校驗

校驗是WEB應用中非常重要的一個環節,如用戶登錄時對有效信息的校驗,購買商品時購物車中商品是否過期校驗等等。

在springmvc中使用hibernate的校驗框架validation(和hibernate沒有任何關係)。

校驗思路:

頁面提交請求的參數,請求到controller方法中,使用validation進行校驗。如果校驗出錯,將錯誤信息展示到頁面。

具體需求:

商品修改,添加校驗(校驗商品名稱長度,生產日期的非空校驗),如果校驗出錯,在商品修改頁面顯示錯誤信息。

二 POM依賴

在pom.xml中添加新依賴:

<!-- hibernate 校驗 -->
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.2.4.Final</version>
</dependency>

三 Springmvc.xml添加配置


<!-- 校驗器 -->
    <bean id="validator"
          class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        <!-- hibernate校驗器-->
        <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="basename" value="CustomValidationMessages">
        </property>
        <!-- 資源文件編碼格式 -->
        <property name="fileEncodings" value="utf-8" />
        <!-- 對資源文件內容緩存時間,單位秒 -->
        <property name="cacheSeconds" value="120" />
    </bean>

校驗器注入到處理器適配器中

<mvc:annotation-driven conversion-service="conversionService"
                       validator="validator">
</mvc:annotation-driven>

在CustomValidationMessages.properties配置校驗錯誤信息:

#添加校驗的錯誤提示信息
items.name.length.error=請輸入1到30個字符的商品名稱
items.createtime.isNUll=請輸入商品的生產日期

四 POJO中添加校驗規則

在items中添加校驗規則

public class Items {
    private Integer id;
    //校驗名稱在1到30字符中間
    //message是提示校驗出錯顯示的信息
    //groups:此校驗屬於哪個分組,groups可以定義多個分組
    @Size(min=1,max=30,message="{items.name.length.error}")
    private String name;

    private Float price;

    private String pic;

    //非空校驗
    @NotNull(message="{items.createtime.isNUll}")
    private Date createtime;

Controller中添加校驗手段

@RequestMapping("/editItemsSubmit")
public String editItemsSubmit(
        Model model,
        HttpServletRequest request,
        Integer id,
        @Validated ItemsCustom itemsCustom,
        BindingResult bindingResult)throws Exception {
//獲取校驗錯誤信息
if(bindingResult.hasErrors()){
    // 輸出錯誤信息
    List<ObjectError> allErrors = bindingResult.getAllErrors();

    for (ObjectError objectError :allErrors){
        // 輸出錯誤信息
        System.out.println(objectError.getDefaultMessage());
    }
    // 將錯誤信息傳到頁面
    model.addAttribute("allErrors", allErrors);

    //可以直接使用model將提交pojo回顯到頁面
    model.addAttribute("items", itemsCustom);

    // 出錯重新到商品修改頁面
    return "items/editItems";
}

頁面顯示錯誤信息

<!-- 顯示錯誤信息 -->
<c:if test="${allErrors!=null }">
    <c:forEach items="${allErrors }" var="error">
        ${ error.defaultMessage}<br/>
    </c:forEach>
</c:if>

五 分組校驗

  • 需求: 
    • 在pojo中定義校驗規則,而pojo是被多個controller所共用,當不同的controller方法對同一個pojo進行校驗,但是每個controller方法需要不同的校驗
  • 解決方法: 
    • 定義多個校驗分組(其實是一個java接口),分組中定義有哪些規則
    • 每個controller方法使用不同的校驗分組
1.校驗分組
public interface ValidGroup1 {
    //接口中不需要定義任何方法,僅是對不同的校驗規則進行分組
    //此分組只校驗商品名稱長度

}

2.在校驗規則中添加分組

//校驗名稱在1到30字符中間
//message是提示校驗出錯顯示的信息
//groups:此校驗屬於哪個分組,groups可以定義多個分組
@Size(min=1,max=30,message="{items.name.length.error}",groups = {ValidGroup1.class})
private String name;
3.在controller方法使用指定分組的校驗
// value={ValidGroup1.class}指定使用ValidGroup1分組的校驗
@RequestMapping("/editItemsSubmit")
public String editItemsSubmit(
        Model model,
        HttpServletRequest request,
        Integer id,
        @Validated(value = ValidGroup1.class)ItemsCustom itemsCustom,
        BindingResult bindingResult)throws Exception {



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章