java 19 lines · 5 steps

Building URIs safely with UriComponentsBuilder in Spring

How Spring's fluent builder assembles an encoded search URL from query, paging, and optional parameters.

Explained by highlit
1public URI buildSearchUri(String query, int page, int size, List<String> tags) {
2 UriComponentsBuilder builder = UriComponentsBuilder
3 .fromUriString("https://api.example.com")
4 .path("/v2/products/search")
5 .queryParam("q", query)
6 .queryParam("page", page)
7 .queryParam("size", size)
8 .queryParam("sort", "relevance,desc");
9 
10 if (tags != null && !tags.isEmpty()) {
11 builder.queryParam("tag", tags.toArray());
12 }
13 
14 return builder
15 .queryParamIfPresent("currency", Optional.ofNullable(defaultCurrency))
16 .encode(StandardCharsets.UTF_8)
17 .build()
18 .toUri();
19}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A fluent builder lets you compose a URL declaratively instead of concatenating fragile strings.
  2. 2Encoding once at build time via encode() prevents malformed URLs from unescaped user input.
  3. 3queryParamIfPresent and Optional express conditional parameters without scattering null checks.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building URIs safely with UriComponentsBuilder in Spring — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code