一、实体类中使用@NotBlank
public class User {
@NotBlank(message="用户名为空")
private String username;
@NotBlank(message="用户ID为空")
private int userid;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
二、修改controller接口
@PostMapping(path = "/add", produces = MediaType.APPLICATION_JSON_VALUE)
public int addUserInfo(@Valid @RequestBody User user) {
logger.info("添加用户信息:", user.toString());
long startTime = System.currentTimeMillis();
int result = userService.addUser(user);
long endTime = System.currentTimeMillis();
logger.info("接口返回:{},调用耗时:{}", result, (endTime - startTime));
return result;
}
参数添加@Valid注解
三、统一异常处理类
@RestControllerAdvice(basePackageClasses={UserController.class})
public class ExceptionControllerAdvicer {
@ExceptionHandler(Exception.class)
public RetResult<Null> handlerArgumentException(MethodArgumentNotValidException exception){
RetResult<Null> retResult=new RetResult<>();
retResult.setRetCode(400);
List<ObjectError> allErrors = exception.getBindingResult().getAllErrors();
StringBuilder stringBuilder=new StringBuilder();
Iterator<ObjectError> iterator = allErrors.iterator();
while (iterator.hasNext()){
stringBuilder.append(iterator.next().getDefaultMessage());
}
retResult.setRetMessage(stringBuilder.substring(0,stringBuilder.lastIndexOf(",")));
return retResult;
}
}
@RestControllerAdvice:指定要扫描的包或者具体类名
@ExceptionHandler(Exception.class):参数是某个异常类的class,代表这个方法专门处理该类异常