天天看點

SpringMVC資料校驗

對前端的校驗大多數通過js在頁面校驗,這種方法比較簡單,如果對安全性考慮,還要在背景校驗。

springmvc使用JSR-303(javaEE6規範的一部分)校驗規範,springmvc使用的是Hibernate Validator(和Hibernate的ORM)

加入Hibernate Validator的jar

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.4.1.Final</version>
</dependency>

<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>1.1.0.Final</version>
</dependency>      

配置springmvc.xml

在spring3之後,任何支援JSR303的validator(如Hibernate Validator)都可以通過簡單配置引入,隻需要在配置xml中加入,這時validatemessage的屬性檔案預設為classpath下的ValidationMessages.properties:

<mvc:annotation-driven      

如果不使用預設,可以使用下面配置:

<mvc:annotation-driven validator="validator"

<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
    <property name="providerClass"  value="org.hibernate.validator.HibernateValidator"/>
    <!--不設定則預設為classpath下的ValidationMessages.properties -->
    <property name="validationMessageSource" ref="validatemessageSource"/>
</bean>
<bean id="validatemessageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <!-- validatemessages.properties檔案 --> 
    <property name="basename" value="classpath:validatemessages"/>  
    <property name="fileEncodings" value="utf-8"/>  
    <property name="cacheSeconds" value="120"/>  
</bean>      

配置validatemessages.properties

#校驗提示資訊,items.name.length.error要寫在java代碼中
items.name.length.error=商品名稱長度錯誤      

校驗bean

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;

    //請輸入商品生産日期
    //通過groups指定此校驗屬于哪個分組,可以指定多個分組
    @NotNull(message="{items.createtime.is.notnull}")
    private      

controller中捕獲錯誤

需要修改controller方法,在要校驗的pojo前邊加上@Validated

public String editItemSubmit(Model model,Integer id,
                @Validated @ModelAttribute(value="itemsCustom") ItemsCustom itemsCustom,
                BindingResult bindingResult
            )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";
        }      

注意:每個校驗的pojo前面必須加@Validated,每個校驗的pojo後面要加bindingResult接受校驗錯誤資訊

分組校驗(常用)

需求:

針對不同的controller方法通過分組校驗達到個性化校驗的目的,修改商品修改功能,隻校驗生産日期不能為空。

第一步:建立分組接口

public interface ValidGroup1 {
    //接口不定義方法,就是隻辨別 哪些校驗 規則屬于該 ValidGroup1分組      
public class Items {  
    //請輸入商品生産日期
    //通過groups指定此校驗屬于哪個分組,可以指定多個分組
    @NotNull(message="{items.createtime.is.notnull}",groups={ValidGroup1.class})
    private      
//在@Validated中定義使用ValidGroup1組下邊的校驗
public String editItemSubmit(Model model,Integer id,
                @Validated(value={ValidGroup1.class}) @ModelAttribute(value="itemsCustom") ItemsCustom itemsCustom,
                BindingResult bindingResult
            )throws Exception{
}