Browse Source

Support Optional in UriComponentsBuilder#queryParam

Closes gh-25951
pull/23650/merge
Rossen Stoyanchev 4 years ago
parent
commit
e66e34766e
  1. 12
      spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java
  2. 22
      spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java

12
spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java

@ -698,7 +698,7 @@ public class UriComponentsBuilder implements UriBuilder, Cloneable { @@ -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 { @@ -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()));

22
spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java

@ -749,14 +749,24 @@ class UriComponentsBuilderTests { @@ -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…
Cancel
Save