为什么UriComponentsBuilder未忽略值为null的查询参数?如何处理?
方案1:使用Spring自带的queryParamIfPresent方法(Spring 5.3+ 推荐)
Spring 5.3及以上版本的UriComponentsBuilder自带了queryParamIfPresent方法,会自动忽略值为null的参数,无需额外判断:
UriComponentsBuilder.fromUriString(BASE) .pathSegment("api") .pathSegment("v1") .queryParamIfPresent("param1", Optional.ofNullable(userId)) .queryParamIfPresent("param2", Optional.ofNullable(productId)) .build().toUriString();
运行后生成的URL会自动过滤掉value为null的param1,完全符合预期效果。
方案2:手动判空添加参数(兼容所有Spring版本)
如果你的Spring版本低于5.3,不支持上述方法,可以手动判断参数是否为null,仅当值非空时调用queryParam添加参数:
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(BASE) .pathSegment("api") .pathSegment("v1"); if (userId != null) { builder.queryParam("param1", userId); } if (productId != null) { builder.queryParam("param2", productId); } String targetUrl = builder.build().toUriString();
方案3:批量过滤参数(适合参数较多的场景)
如果需要处理的查询参数数量很多,可以把参数统一放到Map中,批量过滤掉null值后再批量添加,避免写大量重复的if判断:
// 初始化所有待校验的参数 Map<String, Object> queryParams = new HashMap<>(); queryParams.put("param1", userId); queryParams.put("param2", productId); // 可以继续添加更多参数... UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(BASE) .pathSegment("api") .pathSegment("v1"); // 过滤null值后批量添加参数 queryParams.entrySet().stream() .filter(entry -> entry.getValue() != null) .forEach(entry -> builder.queryParam(entry.getKey(), entry.getValue())); String targetUrl = builder.build().toUriString();
内容的提问来源于stack exchange,提问作者erondem
相关产品推荐
相关产品推荐

