<!--參數校驗--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
若是實體須要兩個實體類接受參數一個爲user一個爲role實體,能夠嵌套驗證 java
@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; }
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; } }
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; }