W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
在Spring MVC中,使用了UriComponentsBuilder
和UriComponents
兩個類來提供一種構(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()
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: