• SpringBoot利用validation做参数校验


    我们在设计后端API接口的时候,对于前端传输的参数通常是要进行校验的,以保证接口能正确处理数据。

    我们可以在代码中,通过if进行条件检测,然后根据检测结果来处理数据

    比如这样

    1. if (account == null) {
    2. throw new Exception("用户名称不能为空");
    3. }

    但是依赖需要验证的代码会很多很杂,写起来也不优雅,所以我们选择用validation库来帮助我们进行字段的校验。

    如何使用

    第一步,添加依赖

    1. org.springframework.boot
    2. spring-boot-starter-validation

    第二步、在接口中需要验证的对象前添加 @Valid 注解

    1. @PostMapping(value = "")
    2. public User create(@RequestBody @Valid UserRequestBean bean) {
    3. return userService.create(bean);
    4. }

    对于验证的对象通过添加注解,进行校验

    1. @Getter
    2. @Setter
    3. public class UserRequestBean {
    4. @NotNull(message = "用户名不能为空")
    5. private String username;
    6. @NotNull(message = "年龄不能为空")
    7. @Range(min = 18, max = 24, message = "年龄要在18-24之间")
    8. private Integer age;
    9. @NotNull(message = "性别不能为空")
    10. @Range(min = 0, max = 1, message = "性别只能是男1女0")
    11. private Integer gender;
    12. @NotEmpty(message = "手机号不能为空")
    13. @Pattern(regexp = "1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\\d{8}", message = "请输入合法的手机号")
    14. private String phone;
    15. private String accessCardNumber;
    16. }

    这里用到了几个注解

    NotNull 不能为null

    Range 范围

    NotEmpty 不能为null,也不能trim之后是length为0

    Pattern 满足对应的正则表达式

    第三步、捕获异常,验证失败的时候统一返回提示信息

    SpringBoot利用ControllerAdvice注解捕获全局异常并返回统一格式数据_LO嘉嘉VE的博客-CSDN博客

    这篇博客介绍了,怎么捕获异常返回统一格式的数据

    捕获参数验证异常 MethodArgumentNotValidException ,并返回数据即可

    1. /**
    2. * 处理接口请求参数验证异常
    3. */
    4. @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    5. @ExceptionHandler(MethodArgumentNotValidException.class)
    6. public ErrorResponseBean handleValidException(HttpServletRequest request, MethodArgumentNotValidException exception) {
    7. StringBuilder message = new StringBuilder();
    8. List allErrors = exception.getBindingResult().getAllErrors();
    9. for (ObjectError error :
    10. allErrors) {
    11. if (message.length() > 0) {
    12. message.append("、");
    13. }
    14. message.append(error.getDefaultMessage());
    15. }
    16. return createErrorBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.value(), message.toString(), request);
    17. }

    进阶用法

    常用注解介绍

    除了上面示例介绍的四个注解,还有一些常用注解如下

    Null 必须为空

    Min 数字最小值

    Max 数字最大值

    Past 必须为过去的一个日期

    Future 必须为将来的一个日期

    Length 字符串长度的范围

    其他验证

    上面例子是对class对象的整体验证,如果是直接传输了一个参数,例如获取列表的搜索字段,直接进行验证,可以直接在Controller中定义规则

    1. @GetMapping
    2. public Page list(@RequestParam @Min(value = 0, message = "页数最少为0") int page,
    3. @RequestParam @Min(value = 1, message = "每页最少条数为1") int size,
    4. @RequestParam(required = false) String username,
    5. @RequestParam(required = false) Integer maxAge,
    6. @RequestParam(required = false) Integer minAge,
    7. @RequestParam(required = false) Integer gender,
    8. @RequestParam(required = false) String phone,
    9. @RequestParam(required = false) String accessCardNumber,
    10. @RequestParam(required = false) String orderParam,
    11. @RequestParam(required = false) String direction) {
    12. return userService.list(page, size, username, maxAge, minAge, gender, phone, accessCardNumber, orderParam, direction);
    13. }

    直接使用注解定义要验证的规则就行。要注意的是,需要在这个类上添加一个注解Validated,这样参数中的注解就会生效了。

    1. @Validated
    2. @RestController
    3. @RequestMapping(value = "/user")
    4. public class UserController

  • 相关阅读:
    商业化广告--体系学习-- 2 -- 行业蓝图篇 -- 广告产品与商业模式
    relational learning关系学习
    Mysql数据库 3.SQL语言 DML数据操纵语言 增删改
    OSS对象存储命令管理、数据迁移
    百战RHCE(第四十六战:运维工程师必会技-Ansible学习1-基础知识讲解)
    (Node笔记)Node.js安装及环境配置——史诗级详细版
    【EI会议2023】12.20之后ddl
    CentOS7和CentOS8 Asterisk 20.0.0 简单图形化界面5--libss7驱动7号信令
    【java|golang】1758. 生成交替二进制字符串的最少操作数
    技术人员应该使用那种搜索引擎?
  • 原文地址:https://blog.csdn.net/dengdaijc/article/details/127912958