DEV Community

Salad Lam
Salad Lam

Posted on

About UriComponentsBuilder and UriComponents

UriComponentsBuilder and UriComponents are the utility class in Spring Framework for building and modifying URLs. Following is the test to show how to use them.

UriComponentsBuilder b1 = UriComponentsBuilder.fromHttpUrl("https://www.example.com/hotels/42?filter=f1&filter=f2&option&query=#hash");
UriComponents c1 = b1.build();
assertEquals("https", c1.getScheme());
assertEquals("www.example.com", c1.getHost());
assertEquals(-1, c1.getPort());
assertEquals(Lists.list("hotels", "42"), c1.getPathSegments());
assertEquals("f1", c1.getQueryParams().getFirst("filter"));
assertNull(c1.getQueryParams().getFirst("option"));
assertEquals("", c1.getQueryParams().getFirst("query"));
assertEquals("hash", c1.getFragment());

UriComponentsBuilder b2 = b1.cloneBuilder();
b2.path("/info");
assertEquals("https://www.example.com/hotels/42/info?filter=f1&filter=f2&option&query=#hash", b2.build().toUriString());

UriComponentsBuilder b3 = b1.cloneBuilder();
b3.replacePath("/info/hotels/42");
assertEquals("https://www.example.com/info/hotels/42?filter=f1&filter=f2&option&query=#hash", b3.build().toUriString());

UriComponentsBuilder b4 = b1.cloneBuilder();
b4.replaceQuery(null);
b4.fragment(null);
b4.userInfo("user1");
assertEquals("https://user1@www.example.com/hotels/42", b4.build().toUriString());

UriComponentsBuilder b5 = b1.cloneBuilder();
b5.queryParam("query", "q1", "q2");
assertEquals("https://www.example.com/hotels/42?filter=f1&filter=f2&option&query=&query=q1&query=q2#hash", b5.build().toUriString());

UriComponentsBuilder b6 = b1.cloneBuilder();
b6.replaceQueryParam("query", "q1", "q2");
assertEquals("https://www.example.com/hotels/42?filter=f1&filter=f2&option&query=q1&query=q2#hash", b6.build().toUriString());

assertEquals("/hotels/42?filter=hot&cold", UriComponentsBuilder.fromUriString("/hotels/42").query("filter={value}").buildAndExpand(Collections.singletonMap("value", "hot&cold")).toUriString());
Enter fullscreen mode Exit fullscreen mode

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →