问题描述
我正在调用支持一堆可选queryparams的下游。
同样,我有时只想添加那些queryparams,但是这样做会很烦人
public Map<Subject,Role> getGrantsForResource(
final String propertyId,final boolean filterByRole
) {
final WebTarget resource;
if (filterByRole) {
resource = ramClient
.path("/v1/resource/{resource}/grants")
.resolveTemplate("resource","resource.property." + propertyId)
.queryParam("role","role.23"); //add queryparam
} else {
resource = ramClient
.path("/v1/resource/{resource}/grants")
.resolveTemplate("resource","resource.property." + propertyId);
//don't add queryparam
}
,如果有多个可选的queryparams,则会导致组合爆炸。
总是添加queryparams,但是在不需要时将值设置为空字符串或null也不起作用-添加具有null值的queryparam会导致NPE,而发送空字符串会导致添加查询参数,但没有价值。
我想出了解决方法
public Map<Subject,final Map<String,String> queryParams
) {
WebTarget resource = ramClient
.path("/v1/resource/{resource}/grants")
.resolveTemplate("resource","resource.property." + propertyId);
for (Map.Entry<String,String> e : queryParams.entrySet()) {
if (e.getValue() == null) {
//don't add queryparam
} else {
resource = resource.queryParam(e.getKey(),e.getValue());
}
}
但是肯定有更好的方法吗?
解决方法
您可以在构建 WebTarget 时跳过空值。
public Map<Subject,Role> getGrantsForResource(
final String propertyId,final Map<String,String> queryParams) {
WebTarget resource = ramClient
.path("/v1/resource/{resource}/grants")
.resolveTemplate("resource","resource.property." + propertyId);
for (Map.Entry<String,String> entry : queryParams.entrySet()) {
if (entry.getValue() != null) {
webTarget = webTarget.queryParam(entry.getKey(),entry.getValue());
}
}
// use webTarget ...
}