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

Spring WebFlux中如何优雅提取URL问号后的完整查询字符串?

在Spring WebFlux中提取URL完整查询串

需求场景

需要提取URL中问号?之后的全部原始查询字符串,例如:

请求地址:

http://localhost:8080/test?some=query|test=whatever,|something

目标结果:

some=query|test=whatever,|something

原始实现

以下代码可以实现需求,但写法不够简洁:

@GetMapping(path = "/test", produces = APPLICATION_JSON_VALUE)
public Mono<String> test(ServerHttpRequest serverHttpRequest) {
    String uri = serverHttpRequest.getURI().toString();
    String queryParam = uri.substring(uri.lastIndexOf("?") + 1);
    return Mono.just(queryParam);
}

更优实现

直接借助ServerHttpRequest的原生API即可完成,代码更简洁且更可靠:

@GetMapping(path = "/test", produces = APPLICATION_JSON_VALUE)
public Mono<String> test(ServerHttpRequest serverHttpRequest) {
    String queryParam = serverHttpRequest.getUri().getRawQuery();
    return Mono.just(queryParam);
}

getRawQuery()方法会直接返回URL中?之后的原始查询串,自动保留所有特殊字符,同时避免了手动截取字符串可能引发的异常(比如URL无?时,原始写法会返回整个URI字符串,而getRawQuery()会返回null,更符合语义)。

内容的提问来源于stack exchange,提问作者Jonathan Hagen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 15:27:45