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();
  1. 使用帶有URI模板的靜態工廠方法

  2. .queryParam,加入欲使用的參數

  3. .encode,針對 URI 進行編碼

  4. .build,完成操作後建立

  5. .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 物件進行編碼。

考慮 " ; ",這在路徑上是合法的,但具有保留的含義。

第一個選項代替 " ; " ,URI變量中帶有"%3B",但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?