springboot之参数校验---------validation 多实体接受参数pom.xml引入依赖 controller实体

2020-12-07 14:29:51 浏览数 (2)

pom.xml引入依赖

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

controller

如果实体需要两个实体类接受参数一个为user一个为role实体,可以嵌套验证

代码语言:javascript复制
@RestController
public class HelloController {
    @RequestMapping("/hello")
    public Object index(@Valid Role role, 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;
    }

实体

User

代码语言:javascript复制
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.List;

public class User {
    private Integer id;
    @NotEmpty(message = "name不能为空")
    private String username;
    @NotEmpty(message = "password不能为空")
    private String password;
    //@NotNull   Integer类型用notnull注解


    private List<SysRole> roles;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public List<SysRole> getRoles() {
        return roles;
    }

    public void setRoles(List<SysRole> roles) {
        this.roles = roles;
    }
}

Role

代码语言:javascript复制
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;



public class SysRole {
    private Integer id;
   @NotEmpty(message = "name不能为空")
    private String name;
   @Valid
   private User user;
    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;
    }

0 人点赞