依赖包
<dependency>
<groupId>javax.validationgroupId>
<artifactId>validation-apiartifactId>
<version>1.1.0.Finalversion>
dependency>
<dependency>
<groupId>org.hibernategroupId>
<artifactId>hibernate-validatorartifactId>
<version>5.1.2.Finalversion>
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区间内 |
CharSequence | 验证注解的元素值是Email,也可以通过正则表达式和flag指定自定义的email格式 |
package com.gz.springmvc;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
/**
*
功能: 用户实体类
*
版本: 1.0
*
开发人员: 弓振
*
创建日期: 2018年4月26日
*
修改日期: 2018年4月26日
*
修改列表:
*/
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
*/
@RequestMapping(value="/beanValid",method=RequestMethod.GET)
public Map beanValid(@Validated User user,BindingResult errors) {
logger.info("【beanValid开始】param user:{}",user);
Map result = new HashMap();
if(errors.hasErrors()){
List errorList = new ArrayList();
for (ObjectError error : errors.getAllErrors()) {
errorList.add(error.getDefaultMessage());
}
Map errorReturn = new HashMap();
errorReturn.put("ERROR", errorList);
return errorReturn;
}
result.put("SUCCESS", "SUCCESS");
return result;
}
}
响应结果:{“ERROR”: [“用户名不能为空”,“用户密码不能为空”]}
Spring Bean校验代码示例
注:如通过以下两种方式获取数据,@Validated将失效
1.用@RequestParam注解获取
2.直接在方法上写入对应的属性名,如:String name
增加方法级验证步骤:
示例:
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
*/
@ExceptionHandler(ConstraintViolationException.class)
@ResponseBody
public Map execption(Exception e,HttpServletRequest request) {
ConstraintViolationException exception = (ConstraintViolationException)e;
Set> errors = exception.getConstraintViolations();
Iterator> itera = errors.iterator();
List errorList = new ArrayList();
while(itera.hasNext()) {
errorList.add(itera.next().getMessage());
}
Map errorReturn = new HashMap();
errorReturn.put("ERROR", errorList);
return errorReturn;
}
/**
* @Description: validator Get请求
* @param name1
* @return Map
*/
@RequestMapping(value="/methodValid",method=RequestMethod.GET)
public Map loginGet(
@NotEmpty(message = "用户名空")
@Length(min = 5, max = 20, message = "用户名太短,应该在{min}--{max}") String name) {
logger.info("【login GET开始】param name:{}",name);
Map result = new HashMap();
result.put("SUCCESS", "SUCCESS");
return result;
}
}
响应结果:{“ERROR”: [“用户名空”]}
Spring 方法级验证校验
spring 自定义参数校验