Skip to content

接收数组参数 ​

在 Web 应用程序中,处理包含数组参数的 HTTP 请求是一项常见的需求。本文将介绍两种处理数组参数的方法:

  1. 使用框架自带的绑定功能(From)
  2. 使用自定义解析逻辑

1. 使用框架自带的绑定功能(From) ​

利用框架提供的注解和自动绑定功能,可以简化数组参数的接收和处理。以下是一个示例方法,展示如何通过 @RequestPath 注解接收数组参数。

示例代码 ​

java
import nexus.io.annotation.RequestPath;
import nexus.io.http.HttpRequest;
import nexus.io.http.HttpResponse;
import nexus.io.http.Resps;
import nexus.io.json.Json;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ArrayController {

  private static final Logger log = LoggerFactory.getLogger(ArrayController.class);

  @RequestPath(value = "/array")
  public HttpResponse array(String[] names, Integer[] ids, int[] primitiveIds, HttpRequest request) throws Exception {
    // 将数组参数转换为格式化的 JSON 字符串,并拼接作为响应内容
    String jsonResponse = Json.toFormatedJson(names) + Json.toFormatedJson(ids) + Json.toFormatedJson(primitiveIds);
    HttpResponse ret = Resps.json(request, jsonResponse);

    // 从请求中获取名为 "names" 的参数数组
    Object[] xx = request.getParamArray("names");
    log.info("Received names array: {}", Json.toFormatedJson(xx));

    return ret;
  }
}

方法说明 ​

  • 方法签名:

    • array 方法通过 @RequestPath 注解映射到 URL 路径 /array。
    • 接收四个参数:
      • String[] names:字符串数组。
      • Integer[] ids:包装类 Integer 数组。
      • int[] primitiveIds:基本类型 int 数组。
      • HttpRequest request:HTTP 请求对象,用于获取额外的请求信息。
  • 方法逻辑:

    1. 生成响应内容:

      • 使用 Json.toFormatedJson 方法将 names、ids 和 primitiveIds 数组转换为格式化的 JSON 字符串。
      • 将这些 JSON 字符串拼接起来,作为响应的内容。
      • 通过 Resps.json 方法创建一个 HttpResponse 对象,包含上述 JSON 内容。
    2. 获取并记录参数数组:

      • 使用 request.getParamArray("names") 方法从请求中获取名为 "names" 的参数数组,并存储在 Object[] xx 中。
      • 使用日志记录工具(log.info)记录 xx 数组的格式化 JSON 表示,便于调试和监控。
    3. 返回响应:

      • 返回包含 names、ids 和 primitiveIds 数组 JSON 表示的 HttpResponse 对象。

HTML 表单示例 ​

前端可以通过 HTML 表单发送数组参数。以下是一个示例表单,展示如何通过多个 input 标签传递数组数据。

html
<form action="/array" method="post">
  <h3>字符串数组</h3>
  <input type="text" name="names" value="kobe" /><br />
  <input type="text" name="names" value="tan" /><br />

  <h3>Integer 数组</h3>
  <input type="text" name="ids" value="11" /><br />
  <input type="text" name="ids" value="22" /><br />

  <h3>int 数组</h3>
  <input type="text" name="primitiveIds" value="55" /><br />
  <input type="text" name="primitiveIds" value="66" /><br />

  <button type="submit">提交</button>
</form>

注意事项 ​

  • 参数名称一致性:确保前端 input 标签的 name 属性与后端方法参数名称一致,以便框架能够正确绑定。
  • 数据类型匹配:前端传递的参数值应与后端接收的数组类型匹配,避免类型转换错误。

2. 使用自定义解析逻辑 ​

有时,使用框架自带的绑定功能可能不够灵活或过于繁琐。此时,可以选择自定义解析请求参数,手动处理数组数据。

示例代码 ​

java
import nexus.io.annotation.RequestPath;
import nexus.io.model.body.RespBodyVo;
import nexus.io.tio.http.common.HttpRequest;

@RequestPath("/api/v1/email")
public class ApiV1EmailController {

  /**
   * 发送邀请邮件
   *
   * @param request HTTP 请求对象
   * @return 响应体,包含处理结果
   */
  public RespBodyVo sendInviteEmail(HttpRequest request) {
    // 获取名为 "ids" 的参数
    String ids = request.getParam("ids");

    // 参数校验
    if (ids == null || ids.trim().isEmpty()) {
      return RespBodyVo.fail("ids 不能为空");
    }

    // 分割参数字符串,转换为 long 类型数组
    String[] split = ids.split(",");
    long[] studentIds = new long[split.length];
    try {
      for (int i = 0; i < split.length; i++) {
        studentIds[i] = Long.parseLong(split[i].trim());
      }
    } catch (NumberFormatException e) {
      return RespBodyVo.fail("ids 格式错误,必须为数字");
    }

    // 返回成功响应,包含转换后的 studentIds 数组
    return RespBodyVo.ok(studentIds);
  }
}

方法说明 ​

  • 方法签名:

    • sendInviteEmail 方法通过 @RequestPath 注解映射到 URL 路径 /api/v1/email/sendInviteEmail。
    • 接收一个参数 HttpRequest request,用于获取请求中的参数。
  • 方法逻辑:

    1. 获取参数:

      • 使用 request.getParam("ids") 方法获取请求中名为 "ids" 的参数值。
    2. 参数校验:

      • 检查 ids 是否为 null 或空字符串,若是,则返回失败响应,提示 "ids 不能为空"。
    3. 参数解析:

      • 使用 split(",") 方法将 ids 字符串按逗号分割,得到一个字符串数组。
      • 创建一个 long[] 类型的数组 studentIds,用于存储转换后的数字。
      • 遍历分割后的字符串数组,使用 Long.parseLong 方法将每个字符串转换为 long 类型,并存入 studentIds 数组。
      • 如果转换过程中发生 NumberFormatException 异常,说明参数格式错误,返回失败响应,提示 "ids 格式错误,必须为数字"。
    4. 返回响应:

      • 使用 RespBodyVo.ok(studentIds) 返回成功响应,包含转换后的 studentIds 数组。

前端请求示例 ​

使用 curl 命令发送 POST 请求,传递 ids 参数。

bash
curl --location --request POST 'http://localhost/api/v1/email/sendInviteEmail' \
--header 'User-Agent: Apifox/1.0.0 (https://apifox.com)' \
--header 'Authorization: Bearer PAfvyWa268y0on8MbxHhfYY21rvi9Sx8' \
--header 'Accept: */*' \
--header 'Host: localhost' \
--header 'Connection: keep-alive' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'ids=1,2,3,4,5,6,7,8,9'

后端响应示例 ​

成功处理请求后,后端返回如下 JSON 响应:

json
{
  "data": [1, 2, 3, 4, 5, 6, 7, 8, 9],
  "code": 1,
  "msg": null,
  "ok": true
}

注意事项 ​

  • 参数格式:确保前端传递的 ids 参数为逗号分隔的数字字符串,例如 "1,2,3,4,5,6,7,8,9"。
  • 异常处理:在参数解析过程中,捕获可能的格式异常,及时返回有意义的错误信息,提升用户体验。
  • 安全性:对传入的参数进行必要的校验和清理,防止潜在的安全风险,如注入攻击。

总结 ​

在 Web 应用程序中,处理数组参数有多种方法。使用框架自带的绑定功能可以简化开发,但在某些情况下,自定义解析逻辑提供了更高的灵活性和控制力。根据具体需求选择合适的方法,确保代码的可维护性和系统的稳定性。

MIT Licensed