Home > OS >  UriComponentsBuilder ignore null query params
UriComponentsBuilder ignore null query params

Time:10-11

I am trying to construct a url UriComponentsBuilder.

UriComponentsBuilder.fromUriString(BASE)
                .pathSegment("api")
                .pathSegment("v1")
                .queryParam("param1", userId) //userId in null
                .queryParam("param2",productId) //productId 12345
                .build().toUriString();

What I got is like below as expected.

"http://localhost/api/v1?param1=&param2=12345"

When one of these query params is null, I do not want that parameter key be part of url at all. So how can I dynamically construct URL when a parameter is null. I expect something like this:

"http://localhost/api/v1?param2=12345"

CodePudding user response:

I think you may want to use UriComponentsBuilder::queryParamIfPresent instead of the function you're currently using.

From the official documentation:

This function will add a query parameter if its value is not Optional::empty. If it's empty, the parameter won't be added at all.

To turn your null into an Optional, use Optional::ofNullable.

Code sample:

UriComponentsBuilder.fromUriString(BASE)
    .pathSegment("api")
    .pathSegment("v1")
    .queryParamIfPresent("param1", Optional.ofNullable(userId)) // UserId is null
    .queryParamIfPresent("param2", Optional.ofNullable(productId)) // ProductId 12345
    .build()
    .toUriString();

This will result in a URI without param1 in its query string. However, param2 will be added to the query string as that one's not empty.

Hope this helps you out.

Cheers!

-T

  • Related