SpringBoot 参数校验

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.测试结果

b13cefdba7064c0c9e35ea9ddb6916ea-image.png


已有 0 条评论

    我有话说: