Add queryParamIfPresent to UriComponentsBuilder

See gh-25951
This commit is contained in:
Robin Roos
2020-10-21 19:18:11 +01:00
committed by Rossen Stoyanchev
parent 51fb49be34
commit 7af726480f
4 changed files with 61 additions and 0 deletions

View File

@@ -21,6 +21,7 @@ import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.springframework.lang.Nullable;
import org.springframework.util.MultiValueMap;
@@ -334,6 +335,12 @@ public class DefaultUriBuilderFactory implements UriBuilderFactory {
return this;
}
@Override
public DefaultUriBuilder queryParamIfPresent(String name, Optional<?> optionalValue) {
this.uriComponentsBuilder.queryParamIfPresent(name, optionalValue);
return this;
}
@Override
public DefaultUriBuilder queryParam(String name, @Nullable Collection<?> values) {
this.uriComponentsBuilder.queryParam(name, values);

View File

@@ -19,6 +19,7 @@ package org.springframework.web.util;
import java.net.URI;
import java.util.Collection;
import java.util.Map;
import java.util.Optional;
import org.springframework.lang.Nullable;
import org.springframework.util.MultiValueMap;
@@ -185,6 +186,15 @@ public interface UriBuilder {
*/
UriBuilder queryParam(String name, Object... values);
/**
* Delegates to {@link #queryParam(String, Object...)} or {@link #queryParam(String, Object...)} if and only if optionalValue has a value.
* No action will be taken, and the query parameter name will not be added, if optionalValue is empty.
* @param name the query parameter name
* @param optionalValue an Optional, either empty or holding the query parameter value.
* @return
*/
UriBuilder queryParamIfPresent(String name, Optional<?> optionalValue);
/**
* Variant of {@link #queryParam(String, Object...)} with a Collection.
* <p><strong>Note: </strong> please, review the Javadoc of

View File

@@ -27,6 +27,7 @@ import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -708,6 +709,20 @@ public class UriComponentsBuilder implements UriBuilder, Cloneable {
return this;
}
@Override
public UriComponentsBuilder queryParamIfPresent(String name, Optional<?> optionalValue) {
if (optionalValue.isPresent()) {
Object value = optionalValue.get();
if (value instanceof Collection) {
queryParam(name, (Collection) value);
}
else {
queryParam(name, value);
}
}
return this;
}
@Override
public UriComponentsBuilder queryParam(String name, @Nullable Collection<?> values) {
return queryParam(name, (CollectionUtils.isEmpty(values) ? EMPTY_VALUES : values.toArray()));