URI 連接工具
UriComponents 對象
UriComponentsBuilder 實作了 UriBuilder。
UriComponents uriComponents =
UriComponentsBuilder
.fromUriString("https://example.com/hotels/{hotel}")
.queryParam("q", "{q}")
.encode()
.build();
URI uri = uriComponents.expand("Westin", "123").toUri();
使用帶有URI模板的靜態工廠方法
.queryParam,加入欲使用的參數
.encode,針對 URI 進行編碼
.build,完成操作後建立
.expand,透過建立完成的 uriComponents 帶入參數,產出 URI。
簡化版
URI uri =
UriComponentsBuilder
.fromUriString("https://example.com/hotels/{hotel}")
.queryParam("q", "{q}")
.encode()
.buildAndExpand("Westin", "123")
.toUri();
URI uri =
UriComponentsBuilder
.fromUriString("https://example.com/hotels/{hotel}")
.queryParam("q", "{q}")
.build("Westin", "123");
URI uri =
UriComponentsBuilder
.fromUriString("https://example.com/hotels/{hotel}?q={q}")
.build("Westin", "123");
預設自帶 URI 編碼
URI uri =
UriComponentsBuilder
.fromUriString("https://example.com/hotels/{hotel}")
.queryParam("q", "{q}")
.build("Westin", "123");
URI 編碼時機
UriComponentsBuilder 提供的 encode():
對URI模板進行預編碼,然後在擴展時嚴格對變量進行編碼。
uriComponents 提供的 encode():
擴展變量(expand)後,才對URI 物件進行編碼。
當前 Servlet 請求
取代傳入參數,並擴展。
ServletUriComponentsBuilder ucb =
ServletUriComponentsBuilder.fromRequest(request)
.replaceQueryParam("accountId", "{id}").build()
.expand("123")
.encode();
相當於 context 的路徑
ServletUriComponentsBuilder ucb =
ServletUriComponentsBuilder.fromContextPath(request)
.path("/accounts")
.build()
Last updated
Was this helpful?