引入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;
}