Stop Manually Concatenating URLs: Master Spring Boot’s Powerful URI Utilities
This article walks through Spring Boot 3.5.0’s URI building tools—including UriComponents, UriBuilderFactory, encoding options, ServletUriComponentsBuilder, and MVC link generation—showing how to construct correct, automatically‑encoded URLs for RestTemplate, WebClient, and controller methods with concrete code examples and outputs.
In Spring Boot development, manually concatenating URLs often leads to encoding errors and malformed paths. Spring’s standard URI building components—UriComponents, UriComponentsBuilder, UriBuilderFactory, and related utilities—provide a systematic way to assemble URLs with automatic encoding and path normalization, compatible with Web MVC.
1. UriComponents
UriComponentsBuilder can build a URI from a template with variables. Example:
UriComponents uriComponents = UriComponentsBuilder
.fromUriString("http://www.pack.com/hotels/{hotel}")
.queryParam("q", "{q}")
.encode()
.buildAndExpand("search", "速八酒店");
System.err.println(uriComponents.toUriString());Output:
http://www.pack.com/hotels/search?q=%E9%80%9F%E5%85%AB%E9%85%92The same can be simplified with URI‑template syntax:
URI uri = UriComponentsBuilder
.fromUriString("http://www.pack.com/hotels/{hotel}?q={q}")
.build("search", "速八酒店");2. UriBuilder and UriBuilderFactory
UriComponentsBuilder implements UriBuilder. A UriBuilderFactory (e.g., DefaultUriBuilderFactory) supplies shared configuration such as base URL and encoding mode, and can be injected into RestTemplate or WebClient.
DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory("http://www.pack.com");
factory.setEncodingMode(EncodingMode.TEMPLATE_AND_VALUES);
RestTemplate restTemplate = new RestTemplate();
restTemplate.setUriTemplateHandler(factory);
restTemplate.setInterceptors(List.of(new ClientHttpRequestInterceptor() {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
ClientHttpRequestExecution execution) throws IOException {
System.err.println(request.getURI());
return execution.execute(request, body);
}
}));
restTemplate.getForObject("/search?q={0}", String.class, "Spring Boot3实战案例300讲");Interceptor prints the full request URI:
http://www.pack.com/search?q=Spring%20Boot3%E5%AE%9E%E6%88%98...WebClient usage:
DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory();
factory.setEncodingMode(EncodingMode.TEMPLATE_AND_VALUES);
WebClient client = WebClient.builder().uriBuilderFactory(factory).build();3. URI Encoding Options
UriComponentsBuilder#encode() pre‑encodes the template and then strictly encodes variables during expansion. UriComponents#encode() encodes each component after variable expansion. The first option also escapes reserved characters inside variables.
URI uri = UriComponentsBuilder.fromPath("/hotel list/{city}")
.queryParam("q", "{q}")
.encode()
.buildAndExpand("wlmq", "200+double bed")
.toUri();
System.err.println(uri);Result: /hotel%20list/wlmq?q=200%2Bdouble%20bed Using a full template simplifies further:
URI uri = UriComponentsBuilder.fromUriString("/hotel list/{city}?q={q}")
.build("wlmq", "200+double bed");
System.err.println(uri);4. ServletUriComponentsBuilder
ServletUriComponentsBuilder creates URIs relative to the current request.
@GetMapping("/current")
public String get(HttpServletRequest request) {
URI uri = ServletUriComponentsBuilder.fromRequest(request)
.replaceQueryParam("id", "{id}")
.build(666);
return uri.toString();
}It can also build from the context path or servlet mapping:
URI uri = ServletUriComponentsBuilder.fromContextPath(request)
.path("/users")
.build()
.toUri(); URI uri = ServletUriComponentsBuilder.fromServletMapping(request)
.path("/users")
.build()
.toUri();5. Building Controller Links
MVC provides MvcUriComponentsBuilder to generate links to controller methods.
@GetMapping("/book")
public String bookUri() {
UriComponents uriComponents = MvcUriComponentsBuilder
.fromMethodName(BookController.class, "getBooking", 666L)
.build();
URI uri = uriComponents.encode().toUri();
return uri.toString();
}6. Using UriBuilder as a Method Parameter
A controller method can accept UriComponentsBuilder to construct URLs based on the current request’s host, port, scheme, etc.
@GetMapping("/get")
public String get(UriComponentsBuilder builder) {
return builder.scheme("http")
.host("www.pack.com")
.port(8088)
.uri(URI.create("/search"))
.build()
.toUriString();
}The article demonstrates each feature with concrete code snippets and the corresponding output, showing how Spring Boot’s URI utilities simplify URL construction, ensure correct encoding, and integrate seamlessly with RestTemplate, WebClient, and MVC.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Spring Full-Stack Practical Cases
Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
