springboot 2.x 中使用@Validated注解对数据进行参数校验

1. bean 中添加标签

@Data
public class MpUserPageDto implements Serializable {

    @JsonIgnore
    @Min(value = 1,message = "页码不能小于1")
    private int pageNum;

    @JsonIgnore
    @Min(value = 1,message = "每页展示数量不能小于1")
    @Max(value = 100,message = "每页展示数量不能大于100")
    private int pageSize;

    private String username;

    private String address;

}

2. Controller中开启校验(至此,成功开启校验)

    @RequestMapping(value = "/page",method = RequestMethod.POST)
    public ReturnVo page(@Validated MpUserPageDto mpUserPageDto) throws Exception {
        Page page = new Page<>(mpUserPageDto.getPageNum(),mpUserPageDto.getPageSize());
        return ReturnVo.success(mpUserService.selectPageExt(page, mpUserPageDto));
    }

3. 由于校验后返回的结果不理想,不符合需要的格式。因此自定义异常类,捕获验证失败的异常

@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 方法参数校验异常
     */
    @ExceptionHandler(BindException.class)
    public ReturnVo handleBindException(BindException e) {
        return ReturnVo.error(ReturnCodeEm.PARAM_ERROR.getCode(), e.getBindingResult().getFieldError().getDefaultMessage());
    }

}

4. 处理后返回结果

{
    "code": 300,
    "msg": "页码不能小于1",
    "data": null
}

参考:https://blog.csdn.net/m0_37542889/article/details/88694739

https://www.cnblogs.com/mr-yang-localhost/p/7812038.html#_label3_3

你可能感兴趣的:(springboot)