You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按原始请求顺序获取GET请求中的所有参数(含重复键)

解决方案:保留GET请求参数的原始顺序

Spring MVC默认会将同名请求参数合并到同一个Key对应的列表中,所以你用LinkedMultiValueMap只能拿到合并后的结果,无法保留参数的原始顺序。要实现需求,需要直接解析请求的原始查询字符串,具体实现如下:

方法:手动解析查询字符串

通过HttpServletRequest获取原始查询字符串,拆分后逐个解析键值对,这样就能完整保留参数的原始顺序:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.AbstractMap;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
public class CheckController {

    @GetMapping("/check")
    @ResponseBody
    public void getCheck(HttpServletRequest request) {
        String queryString = request.getQueryString();
        if (queryString == null) {
            return;
        }

        // 解析查询字符串,保留原始顺序的键值对(String类型)
        List<Map.Entry<String, String>> rawParams = Arrays.stream(queryString.split("&"))
                .map(param -> {
                    String[] keyValuePair = param.split("=", 2);
                    String key = URLDecoder.decode(keyValuePair[0], StandardCharsets.UTF_8);
                    String value = keyValuePair.length > 1 
                            ? URLDecoder.decode(keyValuePair[1], StandardCharsets.UTF_8) 
                            : "";
                    return new AbstractMap.SimpleEntry<>(key, value);
                })
                .collect(Collectors.toList());

        // 转换为Long类型(匹配你的需求)
        List<Map.Entry<String, Long>> longParams = rawParams.stream()
                .map(entry -> new AbstractMap.SimpleEntry<>(
                        entry.getKey(), 
                        Long.parseLong(entry.getValue())
                ))
                .collect(Collectors.toList());

        // 输出原始键值对列表
        System.out.println(longParams);
        
        // 拼接成你需要的格式:{id=[10],id=[1],num=[2],id=[13]}
        String formattedResult = longParams.stream()
                .map(entry -> String.format("%s=[%s]", entry.getKey(), entry.getValue()))
                .collect(Collectors.joining(",", "{", "}"));
        System.out.println(formattedResult);
    }
}

代码说明

  1. 获取原始查询串:request.getQueryString()拿到URL中?后的完整参数序列,比如id=10&id=1&num=2&id=13。
  2. 拆分解码:按&拆分单个参数,再按=拆分键和值,同时做URL解码(处理特殊字符的编码场景)。
  3. 类型转换:将参数值转为Long类型,对齐你原本的参数类型需求。
  4. 格式定制:可根据需要将解析后的键值对拼接成目标格式。

运行后控制台输出示例:

[id=10, id=1, num=2, id=13]
{id=[10],id=[1],num=[2],id=[13]}

内容的提问来源于stack exchange,提问作者Andrei Kernazhytski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 00:35:20