Spring MVC 構(gòu)造URI

2018-07-26 14:15 更新

在Spring MVC中,使用了UriComponentsBuilderUriComponents兩個類來提供一種構(gòu)造和加密URI的機制。

比如,你可以通過一個URI模板字符串來填充并加密一個URI:

UriComponents uriComponents = UriComponentsBuilder.fromUriString(
        "http://example.com/hotels/{hotel}/bookings/{booking}").build();

URI uri = uriComponents.expand("42", "21").encode().toUri();

請注意UriComponents是不可變對象。因此expand()encode()操作在必要的時候會返回一個新的實例。

你也可以使用一個URI組件實例對象來實現(xiàn)URI的填充與加密:

UriComponents uriComponents = UriComponentsBuilder.newInstance()
        .scheme("http").host("example.com").path("/hotels/{hotel}/bookings/{booking}").build()
        .expand("42", "21")
        .encode();

在Servlet環(huán)境下,ServletUriComponentsBuilder類提供了一個靜態(tài)的工廠方法,可以用于從Servlet請求中獲取URL信息:

HttpServletRequest request = ...

// 主機名、schema, 端口號、請求路徑和查詢字符串都重用請求里已有的值
// 替換了其中的"accountId"查詢參數(shù)

ServletUriComponentsBuilder ucb = ServletUriComponentsBuilder.fromRequest(request)
        .replaceQueryParam("accountId", "{id}").build()
        .expand("123")
        .encode();

或者,你也可以選擇只復(fù)用請求中一部分的信息:

    // 重用主機名、端口號和context path
    // 在路徑后添加"/accounts"

    ServletUriComponentsBuilder ucb = ServletUriComponentsBuilder.fromContextPath(request)
            .path("/accounts").build()

或者,如果你的DispatcherServlet是通過名字(比如,/main/*)映射請求的,you can also have the literal part of the servlet mapping included:

    // Re-use host, port, context path
    // Append the literal part of the servlet mapping to the path
    // Append "/accounts" to the path

    ServletUriComponentsBuilder ucb = ServletUriComponentsBuilder.fromServletMapping(request)
            .path("/accounts").build()


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號