javax.validation - BindingResult
作者:互联网
1.书写接收参数参数对象,使用 @NotBlank,@NotNull 注解
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
@Data
public class AbcParam{
@NotBlank(message = "课程名称不能为")
private String title;
@NotNull(message = "价格不能为空")
private Integer price;
}
2.书写 Controller 使用 @Valid 启用参数校验,并使用 参数 BindingResult (作用:使用该参数时,前端参数依然能被注入到abcParam,参数验证失败也不会抛出400,bindingResult 参数包含验证失败信息)
import javax.validation.Valid;
import org.springframework.validation.BindingResult;
@RestController
@RequestMapping(value = "/abc")
public class AbcController {
@PostMapping(value = "/save")
public Object save(@RequestBody @Valid AbcParam abcParam, BindingResult bindingResult){
boolean hasErrors = bindingResult.hasErrors();
if(hasErrors){
List<String> errorMsgList = new ArrayList<String>();
List<FieldError> errors = bindingResult.getFieldErrors();
for (FieldError error:errors) {
String errorMsg = error.getDefaultMessage();
errorMsgList.add(errorMsg);
}
return errorMsgList;
}
return abcParam;
}
}
3.测试,会进入controller
标签:BindingResult,javax,参数,import,validation,bindingResult 来源: https://www.cnblogs.com/abdusalam10/p/11888542.html