1.加入pom支持
<!--springboot 参数校验-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.3.6.Final</version>
</dependency>
2.注入MethodValidationPostProcessor
/**
* springboot 参数校验
* Created by ThinkPad on 2018/4/2.
*/
@Configuration
@EnableAutoConfiguration
public class ValidatorConfig {
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor(){
return new MethodValidationPostProcessor();
}
}
3.实体类校验规则编写
public class Cat {
private Integer id;
@Max(value=100)
@Min(value=0)
private Integer catAge;
@NotNull(message = "catName不能为空")
private String catName;
....
}
4.Controller使用错误处理
@RequestMapping(value = "/addCat",method= RequestMethod.POST)
@ResponseBody
String addCat(@Valid Cat cat,BindingResult bindingResult) throws Exception{
if (bindingResult.hasErrors()) {
List<FieldError> listError = bindingResult.getFieldErrors();
StringBuffer bf = new StringBuffer();
for(FieldError error:listError){
System.out.println(error.getCode()+"---"+error.getArguments()+"---"+error.getDefaultMessage());
bf.append(error.getField()+":"+error.getDefaultMessage());
}
return bf.toString();
}
catService.addCat(cat);
return "添加成功";
}
5.测试结果
注意:本文归作者所有,未经作者允许,不得转载