Support Optional in UriComponentsBuilder#queryParam
Closes gh-25951
This commit is contained in:
parent
5644a7aebb
commit
e66e34766e
|
@ -698,7 +698,7 @@ public class UriComponentsBuilder implements UriBuilder, Cloneable {
|
|||
Assert.notNull(name, "Name must not be null");
|
||||
if (!ObjectUtils.isEmpty(values)) {
|
||||
for (Object value : values) {
|
||||
String valueAsString = (value != null ? value.toString() : null);
|
||||
String valueAsString = getQueryParamValue(value);
|
||||
this.queryParams.add(name, valueAsString);
|
||||
}
|
||||
}
|
||||
|
@ -709,6 +709,16 @@ public class UriComponentsBuilder implements UriBuilder, Cloneable {
|
|||
return this;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
private String getQueryParamValue(@Nullable Object value) {
|
||||
if (value != null) {
|
||||
return (value instanceof Optional ?
|
||||
((Optional<?>) value).map(Object::toString).orElse(null) :
|
||||
value.toString());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UriComponentsBuilder queryParam(String name, @Nullable Collection<?> values) {
|
||||
return queryParam(name, (CollectionUtils.isEmpty(values) ? EMPTY_VALUES : values.toArray()));
|
||||
|
|
|
@ -749,14 +749,24 @@ class UriComponentsBuilderTests {
|
|||
|
||||
@Test
|
||||
void queryParamWithList() {
|
||||
UriComponentsBuilder builder = UriComponentsBuilder.newInstance();
|
||||
UriComponents result = builder.queryParam("baz", Arrays.asList("qux", 42)).build();
|
||||
List<String> values = Arrays.asList("qux", "42");
|
||||
UriComponents result = UriComponentsBuilder.newInstance().queryParam("baz", values).build();
|
||||
|
||||
assertThat(result.getQuery()).isEqualTo("baz=qux&baz=42");
|
||||
MultiValueMap<String, String> expectedQueryParams = new LinkedMultiValueMap<>(2);
|
||||
expectedQueryParams.add("baz", "qux");
|
||||
expectedQueryParams.add("baz", "42");
|
||||
assertThat(result.getQueryParams()).isEqualTo(expectedQueryParams);
|
||||
assertThat(result.getQueryParams()).containsOnlyKeys("baz").containsEntry("baz", values);
|
||||
}
|
||||
|
||||
@Test
|
||||
void queryParamWithOptionalValue() {
|
||||
UriComponents result = UriComponentsBuilder.newInstance()
|
||||
.queryParam("foo", Optional.empty())
|
||||
.queryParam("baz", Optional.of("qux"), 42)
|
||||
.build();
|
||||
|
||||
assertThat(result.getQuery()).isEqualTo("foo&baz=qux&baz=42");
|
||||
assertThat(result.getQueryParams()).containsOnlyKeys("foo", "baz")
|
||||
.containsEntry("foo", Collections.singletonList(null))
|
||||
.containsEntry("baz", Arrays.asList("qux", "42"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
|
Loading…
Reference in New Issue