Spring MVC 構(gòu)造URI

2018-07-26 14:15 更新

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

比如,你可以通過一個(gè)URI模板字符串來(lái)填充并加密一個(gè)URI:

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

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

請(qǐng)注意UriComponents是不可變對(duì)象。因此expand()encode()操作在必要的時(shí)候會(huì)返回一個(gè)新的實(shí)例。

你也可以使用一個(gè)URI組件實(shí)例對(duì)象來(lái)實(shí)現(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類提供了一個(gè)靜態(tài)的工廠方法,可以用于從Servlet請(qǐng)求中獲取URL信息:

HttpServletRequest request = ...

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

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

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

    // 重用主機(jī)名、端口號(hào)和context path
    // 在路徑后添加"/accounts"

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

或者,如果你的DispatcherServlet是通過名字(比如,/main/*)映射請(qǐng)求的,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)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)