UriComponentsBuilder 是 Spring Framework 提供的一个实用工具类,用于构建 URI(Uniform Resource Identifier)。URI 是用于标识和定位资源的字符串,例如 URL(Uniform Resource Locator)就是一种特殊的 URI
UriComponentsBuilder 允许您以一种简单、安全和灵活的方式构建 URI,特别是在处理带有查询参数、路径变量和片段的复杂 URI 时非常有用。
以下是 UriComponentsBuilder 工具的一些主要功能:
- 构建 URI:您可以使用 UriComponentsBuilder来构建 URI。通过添加路径、查询参数、片段等组件,您可以构建完整的 URI
- 路径变量替换:如果 URI 中包含路径变量(例如/users/{userId}),UriComponentsBuilder可以替换路径变量的值
- 添加查询参数:您可以通过queryParam()方法添加查询参数,而不必手动拼接查询字符串。UriComponentsBuilder会处理参数的编码和拼接
- 片段添加:您可以通过 fragment()方法添加片段,用于标识资源的特定部分
- 编码处理:UriComponentsBuilder会自动处理 URI 中的特殊字符,确保生成的 URI 符合规范
使用示例
import org.springframework.web.util.UriComponentsBuilder;
public class UriBuilderExample {
    public static void main(String[] args) {
        // Base URI
        String baseUri = "https://www.example.com";
        // 构建 URI
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(baseUri);
        // 添加路径变量: https://www.example.com/users/{userId}
        builder.path("/users/{userId}");
        // 添加查询参数: https://www.example.com/users/{userId}?name=John&age=30
        builder.queryParam("name", "John")
                .queryParam("age", 30);
        // 添加片段,https://www.example.com/users/{userId}?name=John&age=30#profile
        builder.fragment("profile");
        // 构建最终的 URI,替换 url 中的路径变量:https://www.example.com/users/123?name=John&age=30#profile
        String finalUri = builder.buildAndExpand("123").toUriString();
        System.out.println("Final URI: " + finalUri);
    }
}
上述示例中,UriComponentsBuilder 用于构建一个包含路径变量、查询参数和片段的完整 URI。最终生成的 URI 将是类似于以下格式的字符串:
https://www.example.com/users/123?name=John&age=30#profile
UriComponentsBuilder 提供了一种简单而强大的方式来构建和处理 URI,避免了手动拼接字符串的繁琐和容易出错的问题。在 Spring 应用程序中,它通常用于构建 REST API 的请求 URL 或构造 HTTP 重定向的目标 URL










