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