1. 程式人生 > >Spring validator引數校驗

Spring validator引數校驗

框架整合

依賴包

<dependency>  
     <groupId>javax.validation</groupId>  
     <artifactId>validation-api</artifactId>  
     <version>1.1.0.Final</version>  
 </dependency>  
<dependency>  
     <groupId>org.hibernate</groupId>  
     <artifactId
>
hibernate-validator</artifactId> <version>5.1.2.Final</version> </dependency>

@Valid是javax.validation裡的;@Valid不提供分組功能。
@Validated是@Valid 的一次封裝,是Spring提供的校驗機制使用。

預設校驗引數

JSR提供的校驗註解

註解 適用的資料型別 說明
@AssertFalse Boolean, boolean 驗證註解的元素值是false
@AssertTrue Boolean, boolean 驗證註解的元素值是true
@DecimalMax(value=x) BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence. 驗證註解的元素值小於等於@ DecimalMax指定的value值
@DecimalMin(value=x) BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence. 驗證註解的元素值小於等於@ DecimalMin指定的value值
@Digits(integer=整數位數, fraction=小數位數) BigDecimal, BigInteger, String, byte,short, int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of Number andCharSequence. 驗證註解的元素值的整數位數和小數位數上限
@Future java.util.Date, java.util.Calendar; Additionally supported by HV, if theJoda Time date/time API is on the class path: any implementations ofReadablePartial andReadableInstant. 驗證註解的元素值(日期型別)比當前時間晚
@Max(value=x) BigDecimal, BigInteger, byte, short,int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type ofCharSequence (the numeric value represented by the character sequence is evaluated), any sub-type of Number. 驗證註解的元素值小於等於@Max指定的value值
@Min(value=x) BigDecimal, BigInteger, byte, short,int, long and the respective wrappers of the primitive types. Additionally supported by HV: any sub-type of CharSequence (the numeric value represented by the char sequence is evaluated), any sub-type of Number. 驗證註解的元素值大於等於@Min指定的value值
@NotNull Any type 驗證註解的元素值不是null
@Null Any type 驗證註解的元素值是null
@Past java.util.Date, java.util.Calendar; Additionally supported by HV, if theJoda Time date/time API is on the class path: any implementations ofReadablePartial andReadableInstant. 驗證註解的元素值(日期型別)比當前時間早
@Pattern(regex=正則表示式, flag=) String. Additionally supported by HV: any sub-type of CharSequence. 驗證註解的元素值與指定的正則表示式匹配
@Size(min=最小值, max=最大值) String, Collection, Map and arrays. Additionally supported by HV: any sub-type of CharSequence. 驗證註解的元素值的在min和max(包含)指定區間之內,如字元長度、集合大小
@Valid Any non-primitive type(引用型別) 驗證關聯的物件,如賬戶物件裡有一個訂單物件,指定驗證訂單物件

Hibernate Validator提供的校驗註解:

註解 適用的資料型別 說明
@NotEmpty CharSequence,Collection, Map and Arrays 驗證註解的元素值不為null且不為空(字串長度不為0、集合大小不為0)
@Range(min=最小值, max=最大值) CharSequence, Collection, Map and Arrays,BigDecimal, BigInteger, CharSequence, byte, short, int, long and the respective wrappers of the primitive types 驗證註解的元素值在最小值和最大值之間
@NotBlank CharSequence 驗證註解的元素值不為空(不為null、去除首位空格後長度為0),不同於@NotEmpty,@NotBlank只應用於字串且在比較時會去除字串的空格
@Length(min=下限, max=上限) CharSequence 驗證註解的元素值長度在min和max區間內
@Email CharSequence 驗證註解的元素值是Email,也可以通過正則表示式和flag指定自定義的email格式

Spring Bean校驗

package com.gz.springmvc;

import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;

/**
 * <br/>功能: 使用者實體類
 * <br/>版本: 1.0
 * <br/>開發人員: 弓振
 * <br/>建立日期: 2018年4月26日
 * <br/>修改日期: 2018年4月26日
 * <br/>修改列表:
 */
public class User {

    @NotEmpty(message = "使用者名稱不能為空")  
    @Length(min = 5, max = 20, message = "使用者名稱長度必須在5-20之間") 
    private String name;

    @NotEmpty(message = "使用者密碼不能為空")  
    @Length(min = 5, max = 20, message = "使用者密碼長度必須在5-20之間") 
    private String pwd;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    @Override
    public String toString() {
        return "User [name=" + name + ", pwd=" + pwd + "]";
    }
}
package com.gz.springmvc;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description: validatorController
 * @author gz
 * @date 2018年2月12日
 */
@RestController
public class ValidatorControllerBean {

    private static final Logger logger = LoggerFactory.getLogger(ValidatorControllerBean.class);

    /**
     * @Description: validator 請求
     * @param user
     * @param result1
     * @return Map<String,Object>    
     */
    @RequestMapping(value="/beanValid",method=RequestMethod.GET)
    public Map<String,Object> beanValid(@Validated User user,BindingResult errors) {
        logger.info("【beanValid開始】param user:{}",user);

        Map<String,Object> result = new HashMap<String,Object>();
        if(errors.hasErrors()){
            List<String> errorList = new ArrayList<String>();
            for (ObjectError error : errors.getAllErrors()) {
                errorList.add(error.getDefaultMessage());
            }
            Map<String,Object> errorReturn = new HashMap<String,Object>();
            errorReturn.put("ERROR", errorList);
            return errorReturn;
        }

        result.put("SUCCESS", "SUCCESS");
        return result;
    }

}

響應結果:{“ERROR”: [“使用者名稱不能為空”,”使用者密碼不能為空”]}

Spring 方法級驗證

注:如通過以下兩種方式獲取資料,@Validated將失效

1.用@RequestParam註解獲取
2.直接在方法上寫入對應的屬性名,如:String name

增加方法級驗證步驟:

  1. 將MethodValidationPostProcessor增加到Spring上下中
    <bean class = "org.springframework.validation.beanvalidation.MethodValidationPostProcessor"/>
  2. 上增加@Validated

示例:

package com.gz.springmvc;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description: validatorController
 * @author gz
 * @date 2018年2月12日
 */
@RestController
@Validated
public class ValidatorControllerMethod {

    private static final Logger logger = LoggerFactory.getLogger(ValidatorControllerMethod.class);

    /**
     * @Description: 異常處理
     * @param e
     * @param request
     * @return Map<String,Object>    
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    public Map<String,Object> execption(Exception e,HttpServletRequest request) {
        ConstraintViolationException exception = (ConstraintViolationException)e;
        Set<ConstraintViolation<?>> errors = exception.getConstraintViolations();
        Iterator<ConstraintViolation<?>> itera = errors.iterator();
        List<String> errorList = new ArrayList<String>();
        while(itera.hasNext()) {
            errorList.add(itera.next().getMessage());
        }
        Map<String,Object> errorReturn = new HashMap<String,Object>();
        errorReturn.put("ERROR", errorList);
        return errorReturn;
    }


    /**
     * @Description: validator Get請求
     * @param name1
     * @return Map<String,Object>    
     */
    @RequestMapping(value="/methodValid",method=RequestMethod.GET)
    public Map<String,Object> loginGet(
            @NotEmpty(message = "使用者名稱空") 
            @Length(min = 5, max = 20, message = "使用者名稱太短,應該在{min}--{max}") String name) {
        logger.info("【login GET開始】param name:{}",name);

        Map<String,Object> result = new HashMap<String,Object>();
        result.put("SUCCESS", "SUCCESS");
        return result;
    }

}

響應結果:{“ERROR”: [“使用者名稱空”]}