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提供的校验注解

注解适用的数据类型说明
@AssertFalseBoolean, boolean验证注解的元素值是false
@AssertTrueBoolean, 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.验证注解的元素值的整数位数和小数位数上限
@Futurejava.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值
@NotNullAny type验证注解的元素值不是null
@NullAny type验证注解的元素值是null
@Pastjava.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(包含)指定区间之内,如字符长度、集合大小
@ValidAny non-primitive type(引用类型)验证关联的对象,如账户对象里有一个订单对象,指定验证订单对象

Hibernate Validator提供的校验注解:

注解适用的数据类型说明
@NotEmptyCharSequence,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验证注解的元素值在最小值和最大值之间
@NotBlankCharSequence验证注解的元素值不为空(不为null、去除首位空格后长度为0),不同于@NotEmpty,@NotBlank只应用于字符串且在比较时会去除字符串的空格
@Length(min=下限, max=上限)CharSequence验证注解的元素值长度在min和max区间内
@EmailCharSequence验证注解的元素值是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 Bean校验代码示例

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”: [“用户名空”]}

Spring 方法级验证校验


spring 自定义参数校验

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值