一般项目中,Controller层会使用到BasicController作为父类,里面封装了一些常用的从页面获取登陆信息的方法;
在springBoot中,我们可以使用@NotNull,@NotBlank等注解实现校验
只要在Controller层方法参数前加上@Valid注解即可
1.在VO中使用注解,并自定义message信息
public class PrepPayAddVO {
private String orgId;
private String customerId;
private Integer billType;
private String createId;
private String remark;
@NotNull(message = "交易金额不能为空")
private BigDecimal transactionAmount;
//get/set方法略去
}
2.Controller层,继承了BasicController中的方法,使用actionResultWithBindingResult进行返回。
public class PrepPayController extends BasicController {
@RequestMapping(value = "/add",method = RequestMethod.POST)
@ApiOperation(value = "新增结算卡记录")
@FastMappingInfo(needLogin = true)
public ActionResult add(@Valid @RequestBody PrepPayAddVO prepPayAddVO,BindingResult bindingResult)throws Exception {
if(bindingResult.hasErrors() ){
return actionResultWithBindingResult(ErrorCode.Failure,bindingResult);
}
ErrorCode ret=prepPayService.add(prepPayAddVO,getUserId(),getOrgId());
return actionResult(ret);
}
}
3.在BasicController的处理中,如果注解中自定义了错误信息message,就用它来替代Error的描述:
public <T> ActionResult actionResultWithBindingResult(ErrorCode code, BindingResult bindingResult){
String errMsg = getBindingResultErrors(bindingResult);
if(StringUtils.isBlank(errMsg)){
return actionResult(code);
}
return actionResultDesc(code, errMsg);
}
4.用于获取注解中自定义message的函数:
public String getBindingResultErrors(BindingResult bindingResult){
if (null == bindingResult || !bindingResult.hasErrors()) {
return StringUtils.EMPTY;
}
StringBuilder errorStrBuilder = new StringBuilder();
List<ObjectError> errorList = bindingResult.getAllErrors();
for (ObjectError error : errorList) {
errorStrBuilder.append(error.getDefaultMessage() + ";");
}
return StringUtils.removeEnd(errorStrBuilder.toString(), ";");
}
public <T> ActionResult<T> actionResultDesc(ErrorCode code, T value){
if (code != ErrorCode.Success
&& value != null
&& StringUtils.isNotBlank(value.toString())) {
return new ActionResult<>(code.getCode(),
value.toString(),
value);
}
return new ActionResult<>(code.getCode(),
code.getDesc(),
value);
}