博客

SpringBoot 参数校验

2020-07-01 8987 0

简介 1.加入pom支持 <!--springboot 参数校验--> <dependency> <groupId>org.hibernate</groupId> <artifactId>h...

标签 # 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

标签云

文章评论

欢迎您:

博客

与其用泪水悔恨今天,不如用汗水拼搏今天。

168 文章 2364985 浏览 3 评论

标签云

站点信息

  • 建站时间:2020-10-01
  • 更新时间:2026-11-09
  • 文章统计:168篇文章
  • 标签总数:166个
  • 加我微信:扫码,加我微信

目录