java后端优雅进行参数校验
利用注解的方式进行验证前端传入参数:
public class UavAddDto {
// import javax.validation.constraints.*;
@NotNull(message = "姓名不允许为null")
@NotEmpty(message = "姓名不允许为空,请检查后重新重新传入值")
public String name;
@NotNull(message = "传入数据不允许为空")
@Min(value = 0, message = "传入数据有误,数据必须在 0~100之内")
@Max(value = 100, message = "传入数据有误,数据必须在 0~100之内")
public Integer count;
@Email(message = "传入邮件格式有误,请检查")
public String email;
@Length(min = 11, max = 11, message = "传入的电话号码长度有误,必须为11位")
public String mobile;
}
加上 @Valid 注解,开启对传入对象的验证
@RestController
public class UavController {
@Autowired
private UavService uavService;
@PostMapping("/add")
public String add(@RequestBody @Valid UavAddDto uavAddDto) {
uavService.saveOne(uav);
return "Success";
}
验证对传入参数的检查结果:
结果返回的结果太长,不符合我们传递给前端的结果。
这里我们做全局的异常拦截,只将错误的信息返回给前端。
@ControllerAdvice
@ResponseBody
public class GlobalExceptionInterceptor {
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public ExecutionResponse exceptionHandler(HttpServletRequest request, Exception e) {
ExecutionResponse executionResponse = new ExecutionResponse();
String failMsg = null;
if (e instanceof MethodArgumentNotValidException) {
// 拿到参数校验具体异常信息提示
failMsg = ((MethodArgumentNotValidException) e).getBindingResult().getFieldError().getDefaultMessage();
executionResponse.setFailed(failMsg);
}
// 将消息返回给前端
return executionResponse;
}
}
返回体:
// 返回体 这里用了 lombok 插件
@Getter
@Setter
public class ExecutionResponse {
private Integer code = ResponseCodeEnum.RESPONSE_SUCCESS.code() ;
private String message = "操作成功";
public void setFailed(String message){
this.code = ResponseCodeEnum.RESPONSE_FAILED.code();
this.message = message;
}
}
添加异常拦截器后结果为:

这样就优雅的将错误结果返回给前端。
本文介绍了一种优雅的Java后端参数校验方法,通过使用注解验证前端传入的参数,包括姓名、计数、电子邮件和电话号码。文章详细展示了如何在DTO中应用@NotNull、@NotEmpty、@Min、@Max、@Email和@Length注解,并通过@Valid注解启动对象验证。同时,文中还介绍了如何通过全局异常拦截器精简错误信息,使其更适于前端展示。
2330

被折叠的 条评论
为什么被折叠?



