@Valid
在pom.xml里面,添加依赖(直接添加这个对springboot的依赖即可)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
实体类加入限制例如@NotNull
@Data
public class Request implements Serializable {
@Min(value = 1,message = "id需要大于1")
@NotNull(message = "id不能为null")
private Integer id;
@NotNull(message = "name不能为null")
private String name;
}
Controller层添加@Valid,和捕捉一下错误信息(BindingResult)【实际其实需要构造其他通用返回处理】
@RestController
public class DemoController {
@PostMapping("/test")
public String get(@RequestBody @Valid Request request, BindingResult bindingResult){
if (bindingResult.hasErrors()) {
List<ObjectError> allErrors = bindingResult.getAllErrors();
List<String> errMessages = allErrors.stream().map(r -> r.getDefaultMessage()).collect(Collectors.toList());
return errMessages.toString();
}
return request.toString();
}
}
评论区