Format Collection query param in UriComponentsBuilder

See gh-34311

Signed-off-by: Mengqi Xu <2663479778@qq.com>
This commit is contained in:
Mengqi Xu
2025-01-23 21:37:23 +08:00
committed by rstoyanchev
parent b07ff1c2d4
commit 295a9565a3
2 changed files with 27 additions and 0 deletions

View File

@@ -22,6 +22,7 @@ import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
@@ -47,6 +48,7 @@ import org.springframework.util.StringUtils;
* @author Rossen Stoyanchev
* @author Phillip Webb
* @author Sam Brannen
* @author Mengqi Xu
* @since 3.1.3
* @see <a href="https://tools.ietf.org/html/rfc3986#section-1.2.3">Hierarchical URIs</a>
*/
@@ -1090,6 +1092,9 @@ final class HierarchicalUriComponents extends UriComponents {
if (ObjectUtils.isArray(value)) {
value = StringUtils.arrayToCommaDelimitedString(ObjectUtils.toObjectArray(value));
}
if (value instanceof Collection<?> coll) {
value = StringUtils.collectionToCommaDelimitedString(coll);
}
return value;
}
}

View File

@@ -23,6 +23,7 @@ import java.io.ObjectOutputStream;
import java.net.URI;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
@@ -42,6 +43,7 @@ import static org.springframework.web.util.UriComponentsBuilder.fromUriString;
* @author Arjen Poutsma
* @author Phillip Webb
* @author Rossen Stoyanchev
* @author Mengqi Xu
*/
class UriComponentsTests {
@@ -153,6 +155,26 @@ class UriComponentsTests {
assertThat(uri.toUriString()).isEqualTo("https://example.com/foo#bar");
}
@Test
void expandQueryParamWithArray() {
UriComponents uri = UriComponentsBuilder.fromPath("/hello")
.queryParam("name", "{name}")
.build();
uri = uri.expand(Collections.singletonMap("name", new String[]{"foo", "bar"}));
assertThat(uri.toString()).hasToString("/hello?name=foo,bar");
}
@Test
void expandQueryParamWithList() {
UriComponents uri = UriComponentsBuilder.fromPath("/hello")
.queryParam("name", "{name}")
.build();
uri = uri.expand(Collections.singletonMap("name", List.of("foo", "bar")));
assertThat(uri.toString()).hasToString("/hello?name=foo,bar");
}
@ParameterizedTest // SPR-12123
@EnumSource
void port(ParserType parserType) {