springboot之参数校验---------validation引入jar实体类controller

2020-12-07 14:29:32 浏览数 (1)

引入jar

代码语言:javascript复制
<!--参数校验-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>

实体类

代码语言:javascript复制
public class user{
    private Integer id;
   @NotEmpty(message = "name不能为空")
    private String name;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

controller

代码语言:javascript复制
@RestController
public class HelloController {
    @RequestMapping("/hello")
    public Object index(@Valid User user, BindingResult bindingResult){
        List<ObjectError> error=null;
     //返回boolean 是为了验证@Validated后面bean 里是否有不符合注解条件的错误信息
     if(bindingResult.hasErrors()){
         //获得所有错误信息返回list集合
         error=bindingResult.getAllErrors();
         for (ObjectError o:error) {
             //获得不符合要求的message
             return o.getDefaultMessage();
         }

     }
        return null;
    }

0 人点赞