1.配置pom.xml
<!-- hibernate-validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.1.Final</version>
</dependency>
2.配置spring-mvc.xml
<!-- validation -->
<bean class="org.springframework.validation.beanvalidation.MethodValidationPostProcessor"/>
3.建立统一处理
/**
* @Author : xiao
* @Date : 17/5/10 下午2:56
*/
@ControllerAdvice
@ResponseBody
public class ExceptionAdvice {
private static Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);
/**
* 400 - Bad Request
*/
// @ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public String handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
logger.error("参数验证失败", e);
BindingResult result = e.getBindingResult();
List<String> resultList = new ArrayList<String>();
for (ObjectError error : result.getAllErrors()) {
String code = error.getCode();
String message = error.getDefaultMessage();
String description = String.format("%s:%s", code, message);
resultList.add(message);
}
return new CommonResult().failure(resultList, ResultStatusEnum.PARAMETER_INVALID.getCode(),
ResultStatusEnum.PARAMETER_INVALID.getDescription()).toJSON();
}
}
4.测试mode
package com.jeiker.boss.model.hello;
import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.Range;
/**
* @Author : xiao
* @Date : 17/5/10 下午2:51
*/
public class UserVO {
/**
* Bean Validation 中内置的 constraint
*
* @Null 被注释的元素必须为 null
* @NotNull 被注释的元素必须不为 null
* @AssertTrue 被注释的元素必须为 true
* @AssertFalse 被注释的元素必须为 false
* @Min(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
* @Max(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
* @DecimalMin(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
* @DecimalMax(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
* @Size(max=, min=) 被注释的元素的大小必须在指定的范围内
* @Digits(integer, fraction) 被注释的元素必须是一个数字,其值必须在可接受的范围内
* @Past 被注释的元素必须是一个过去的日期
* @Future 被注释的元素必须是一个将来的日期
* @Pattern(regex=,flag=) 被注释的元素必须符合指定的正则表达式
*
* Hibernate Validator 附加的 constraint
*
* @NotBlank(message =) 验证字符串非null,且长度必须大于0
* @Email 被注释的元素必须是电子邮箱地址
* @Length(min=,max=) 被注释的字符串的大小必须在指定的范围内
* @NotEmpty 被注释的字符串的必须非空
* @Range(min=,max=,message=) 被注释的元素必须在合适的范围内
*/
@NotEmpty(message="姓名不能为空")
private String name;
@Range(min=20,max=120,message="年龄在20到120岁之间")
private int age;
@NotEmpty(message="地址不能为空")
private String address;
... getter
... setter
}
5.测试Controller
@Controller
@RequestMapping(value = "/operation/hello")
public class HelloController {
public static final Logger LOG = LoggerFactory.getLogger(HelloController.class);
@RequestMapping(value = "/testValidUser", method = RequestMethod.POST)
@ResponseBody
public String testValidUser(@RequestBody @Valid UserVO userVO){
return CommonResult.success(userVO).toJSON();
}
}
6.测试结果
POST:
http://localhost:8080/operation/hello/testValidUser
{
"name":"",
"age":130,
"address":""
}
结果:
{
"data": [
"年龄在20到120岁之间",
"姓名不能为空",
"地址不能为空"
],
"message": "参数不合法",
"status": 11010
}