spring boot 校验请求json参数

在后端开发中,通过接口和参数传输来进行与前端交互,才可以让一个项目成型。

由于全后端隔离的方式,所以有时候需要不那么信任前端,也就是在验证当前操作是否有权限同时,校验前端传来的参数的合理性也是必不可少的。

这里只记录post json数据时候的校验方法。


以下代码中使用到的依赖,以及工具类,在结果的git链接中可以找到


  1. 一般的校验方法

    代码:

    // 测试接口
    @RestController
    @RequestMapping("/simple")
    public class SimpleController { // 开发中建议另外定义一个类来接受=收
    // 可以使用内部类, 不过不要写太多
    @Data
    private static class TestParam {
    private int num;
    private String str;
    } @PostMapping("/test")
    public R<?> test(@RequestBody(required = false) TestParam param) { if (StringUtils.isNull(param)
    || StringUtils.isEmpty(param.getStr()) || param.getNum() <= 0) {
    return R.paramErr();
    } // TODO 逻辑处理 return R.ok(new JSONObject());
    }
    }

    测试参数:

    {
    
    }
    or
    {
    "str": 1
    }
    or
    {
    "num": 2
    }

    结果:

    {
    "code": "1001",
    "msg": "参数格式错误",
    "data": null
    }

    结果以及分析:

    • 表述不清楚,不管是缺少,还是不符合格式,全部返回格式错误(单独判断很冗余)。
    • 在str传输数字时候可以通过(给数字类型传纯字符串的处理方法在2.2第第二个处理器)
  2. 接下来记录springboot提供的参数校验注解

      <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
    <version>2.5.6</version>
    </dependency>
    1. 参数注解

      @Data
      private static class TestParam {
      @Min(value = 1L, message = "数字参数最小值不能小于1")
      @NotNull(message = "缺少数字参数")
      private int num; @NotNull(message = "缺少字符串参数")
      private String str; @NotNull(message = "对象参数不能为空")
      @Valid
      private TestObjParam obj;
      } @Data
      public static class TestObjParam {
      @NotNull(message = "对象参数内,参数不能为空")
      // 若还有内部对象,继续使用 @Valid 注解即可
      private String param; @NotEmpty(message = "数组不能为空")
      private List<String> stringList; @Size(max = 2, min = 0, message = "性别参数必须在0-2之间")
      private int gender;
      } @PostMapping(value = "/test")
      Object test(@RequestBody @Validated TestParam param) {
      return "通过测试";
      }
    2. 与之配套使用的

      @RestControllerAdvice
      public class ControllerAdvice { /**
      * 拦截JSON参数校验
      */
      @ResponseStatus(HttpStatus.OK)
      @ExceptionHandler(MethodArgumentNotValidException.class)
      public Map<String, String> bindException(MethodArgumentNotValidException e) { BindingResult bindingResult = e.getBindingResult(); String msg = Objects.requireNonNull(
      bindingResult.getFieldError()).getDefaultMessage(); Map<String, String> result = new HashMap<>(); result.put("code", "1001");
      result.put("msg", msg);
      result.put("data", null); return result;
      } /**
      * 拦截类型不匹配。也即需要字段传对象,数字传字符串和对象的情况
      */
      @ResponseStatus(HttpStatus.OK)
      @ExceptionHandler(HttpMessageNotReadableException.class)
      public R<?> bindException(HttpMessageNotReadableException e) { return R.paramErr("参数中有不符合目标格式的");
      }
      }
    3. 结果分析

      • 大大减少了在进行逻辑开发前的手动参数校验
      • 同时前端在对接口时候也可以准确地清楚参数缺少和不符合要求的情况。
  3. 常用的参数,完整版可以在包javax.validation.constraints中

    注解 解释 所修饰类型
    @NotNull 被注解的元素不能为null 修饰所有类型参数
    @NotEmpty 不能为空 数组
    @Min(value) 被注解元素的最小值等于value 数字类型
    @Max(value) 被注解的元素的最大值等于value 数字类型
    @Size(max, min) 大小注解 数组
    @Pattern(value) 正则表达式做鉴定
  4. git地址: springboot-param-validate

  5. 补充:

    • @Range校验数字范围
    • @Length校验字符串长度
    • @Size校验String和数组长度
    • @Digits(integer = 6, fraction = 0, message = "") 修饰数字(整数位数和小数位数)
    • @BigDecimalMax和min可配合Digits
  6. 参考资料:


2022-11-17 补充分组



@Validated与@Validate的简要区别:

  1. @Validated校验的对象中如果有对象类型的属性, 该属性上需要用@Validate, 可进行校验传递
  2. @Validated可进行分组校验, @Validate无分组校验.

    分组:

import javax.validation.GroupSequence; /**
* 至于interface与@interface在此处的区别, 并未得知
* 参考:
* <a href="https://blog.csdn.net/weixin_45941064/article/details/124192836">Java @interface和interface的区别</a>
* <a href=" https://reflectoring.io/bean-validation-with-spring-boot">Validation with Spring Boot - the Complete Guide</a>
* <a href="https://nullbeans.com/how-to-use-java-bean-validation-in-spring-boot/">How to use Java Bean Validation in Spring Boot</a>
* <a href="https://gitee.com/bootx/bootx-platform">bootx-platform, @cn.bootx.common.core.validation</a>
*
* @author wangXiaoMing
* @date 2022/11/14 17:51
*/
public interface ValidationGroup { /**
* 参数校验分组:添加
*/
@interface create {
} /**
* 参数校验分组:修改
*/
@interface update {
} /**
* 参数校验分组:添加修改 - 也可使用序列
*/
@interface createUpdate {
} /**
* 参数校验分组:删除
*/
@interface delete {
} /**
* 参数校验分组:查询
*/
@interface query {
} /**
* 先校验update, 再校验delete, 然后时create
* 代表校验顺序, 和需要校验的分组
* <p>
* 参考:
* <a href="https://blog.csdn.net/qq_17586821/article/details/104661914">validation-api中@GroupSequence的使用</a>
* <a href="https://blog.csdn.net/chepeng3577/article/details/100719210">@GroupSequence自定义验证顺序</a>
* <a href="https://blog.csdn.net/linxingliang/article/details/122044749">validation数据校验之分组校验怎么玩?</a>
*/
@GroupSequence({update.class, delete.class, create.class})
@interface order {
} }

使用:

多个分组时需要使用{}, 单个时可省略

@NotNull(message = "id不能为空1", groups = {ValidationGroup.create.class})

Controller中使用时@Validated({ValidationGroup.create.class})进行校验

分组序列@GroupSequence的使用:

  1. 指定包含的分组(其他分组不会校验, 如上面的query和createUpdate)
  2. 以及校验的对应的顺序

SpringBoot校验请求Json参数的更多相关文章

  1. 逐层解析请求json参数字符串【我】

    import net.sf.json.JSONObject; 逐层解析请求json参数字符串: InputStream inStream =null; BufferedReader br =null; ...

  2. SpringBoot获取请求的参数

    说明 SpringBoot 为我们封装了许多,简便的获取请求参数的方法! 1.获取无注解获取请求参数 请求地址:http://192.168.0.115:8080/myproject/test/noA ...

  3. SpringBoot:自定义注解实现后台接收Json参数

    0.需求 在实际的开发过程中,服务间调用一般使用Json传参的模式,SpringBoot项目无法使用@RequestParam接收Json传参 只有@RequestBody支持Json,但是每次为了一 ...

  4. SpringBoot配置Swagger实例(POST接收json参数)

    工程目录结构: 首先,引入jar包,只需要以下两个即可 <dependency> <groupId>io.springfox</groupId> <artif ...

  5. play framework接收post请求json格式的参数

    大家在用play framework框架开发第三方调用你的接口的时候并且用json格式的参数post请求 ,参数接收是个问题 ,因为play对表单提交post请求有处理: 有两种方法: 1.直接形参列 ...

  6. C# ContentType: "application/json" 请求方式传json参数问题

    处理Http请求时遇到的ContentType为application/json方式,记录下这种Post请求方式下如何传json参数: var request = (HttpWebRequest)We ...

  7. ②HttpURLConnection通过Json参数方式提交Post请求

    之前的文章介绍过通过报文的方式HttpURLConnection提交post请求,今天介绍下通过Json参数的方法提交Post请求,先上代码 public static HttpResponse se ...

  8. ReadyAPI/soapUI发送post请求json格式(带有中文字符),后台获取参数为空

    解决:请求编码格式默认为空,在"TestCase"的指定Step的Request Properties中, 改Encoding编码格式为UTF-8. 原文:soapUI发送post ...

  9. curl 使用 post 请求,传递 json 参数,下载文件

    curl -X POST http://ip:8888/nacos/v1/cs/file/download -H "Accept: application/octet-stream" ...

  10. 1. 处理静态资源 2. controller如何接受请求得参数 3. 如何把controller得数据保存到view. 4. 在controller如何完成重定向到指定路径 5. controller返回json数据

    1. 1. 处理静态资源2. controller如何接受请求得参数3. 如何把controller得数据保存到view.4. 在controller如何完成重定向到指定路径5. controller ...

随机推荐

  1. w3cschool-Spring Security

    https://www.w3cschool.cn/springsecurity/na1k1ihx.html Spring Security,这是一种基于 Spring AOP 和 Servlet 过滤 ...

  2. JAVA调用groovy脚本的方式

    一.使用用 Groovy 的 GroovyClassLoader ,它会动态地加载一个脚本并执行它.GroovyClassLoader是一个Groovy定制的类装载器,负责解析加载Java类中用到的G ...

  3. C#/.NET/.NET Core技术前沿周刊 | 第 21 期(2025年1.6-1.12)

    前言 C#/.NET/.NET Core技术前沿周刊,你的每周技术指南针!记录.追踪C#/.NET/.NET Core领域.生态的每周最新.最实用.最有价值的技术文章.社区动态.优质项目和学习资源等. ...

  4. 使用TUniSQLMonitor监视SQL语句执行的耗时

    //代码来自官方论坛type TUniSqlMonitorEx = class(TUniSqlMonitor) private FExecuteDuration: Cardinal; FFinalEv ...

  5. 独立开发经验谈:如何通过 Docker 让潜在客户快速体验你的系统

    我在业余时间开发了一款自己的独立产品:升讯威在线客服与营销系统.陆陆续续开发了几年,从一开始的偶有用户尝试,到如今线上环境和私有化部署均有了越来越多的稳定用户,在这个过程中,我也积累了不少如何开发运营 ...

  6. Serverless函数计算介绍

    本文分享自天翼云开发者社区<Serverless函数计算介绍>,作者:余凯 随着互联网和移动互联网的快速发展,越来越多的应用程序需要具备高可用性.高扩展性和高性能等特点.而云计算作为一种新 ...

  7. Linux iostat 命令详解

    Linux iostat 命令详解 在Linux系统管理中,监控磁盘I/O性能是一项至关重要的任务.iostat是sysstat包中的一个实用工具,用于监控和显示系统输入输出设备和CPU的使用情况.它 ...

  8. Linux环境下安装phantomjs

    一.创建文件夹,用来存放软件 cd /opt/softWare mkdir  phantomJS cd phantomJS 二.下载并解压 wget https://bitbucket.org/ari ...

  9. SpringBoot利用@Async注解实现异步调用

    前言:异步编程是让程序并发运行的一种手段,使用异步编程可以大大提高我们程序的吞吐量,减少用户的等待时间.在Java并发编程中实现异步功能,一般是需要使用线程或者线程池.而实现一个线程,要么继承Thre ...

  10. Datagrip 破解

    题记部分 方法一 [参考链接]:DataGrip 2023.2最新安装使用教程(附激活码,亲测好用)_糖果果爱分享的技术博客_51CTO博客 [软件版本]:datagrip-2023.3.4.win ...