java - 为什么 UriComponentsBuilder 忽略空查询参数?

标签 java spring-mvc

我正在尝试构造一个 url UriComponentsBuilder

UriComponentsBuilder.fromUriString(BASE)
                .pathSegment("api")
                .pathSegment("v1")
                .queryParam("param1", userId) //userId in null
                .queryParam("param2",productId) //productId 12345
                .build().toUriString();

我得到的结果如下所示。

"http://localhost/api/v1?param1=&param2=12345"

当这些查询参数之一为空时,我根本不希望该参数键成为 url 的一部分。那么当参数为空时,如何动态构造 URL。我期待这样的事情:

"http://localhost/api/v1?param2=12345"

最佳答案

我想你可能想使用 UriComponentsBuilder::queryParamIfPresent而不是您当前正在使用的功能。

来自官方文档:

This function will add a query parameter if its value is not Optional::empty. If it's empty, the parameter won't be added at all.

要将您的 null 转换为 Optional,请使用 Optional::ofNullable

代码示例:

UriComponentsBuilder.fromUriString(BASE)
    .pathSegment("api")
    .pathSegment("v1")
    .queryParamIfPresent("param1", Optional.ofNullable(userId)) // UserId is null
    .queryParamIfPresent("param2", Optional.ofNullable(productId)) // ProductId 12345
    .build()
    .toUriString();

这将导致在其查询字符串中没有 param1 的 URI。 但是,param2 将被添加到查询字符串中,因为它不是空的。

希望这对你有帮助。

干杯!

-T

关于java - 为什么 UriComponentsBuilder 忽略空查询参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69515861/

相关文章:

java - 使用 JAVA 将 CSV 文件转换为 Hierarchy XML

java - 如何在Spring-xd中上传模块?

java - Spring 数据 REST : custom methods validation

java - Spring 安全不适用于 angularJS

java - 语法错误: Unexpected token s in JSON at position 0 at JSON.解析+ angularjs

java - 无法删除 ActiveMQ ScheduledMessage?

java - SQLite。数字排序

java - Android 客户端和 Windows 服务器之间的 TCP 连接在随机时间后中断

java - 当 Java 应用程序位于负载均衡器后面时,在某些 URL 上强制使用 SSL

java - Java Web中如何配置文件路径或者url路径,有时需要加反斜杠有时不需要加?