springboot之引數校驗---------validation 多實體接受引數
阿新 • • 發佈:2022-03-07
pom.xml引入依賴 <!--引數校驗--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency> controller 如果實體需要兩個實體類接受引數一個為user一個為role實體,可以巢狀驗證 @RestController public classHelloController { @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 import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import java.util.List; public class User { privateInteger 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 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; }