W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
Spring MVC也提供了構(gòu)造指定控制器方法鏈接的機制。以下面代碼為例子,假設(shè)我們有這樣一個控制器:
@Controller
@RequestMapping("/hotels/{hotel}")
public class BookingController {
@RequestMapping("/bookings/{booking}")
public String getBooking(@PathVariable Long booking) {
// ...
}
}
你可以通過引用方法名字的辦法來準(zhǔn)備一個鏈接:
UriComponents uriComponents = MvcUriComponentsBuilder
.fromMethodName(BookingController.class, "getBooking", 21).buildAndExpand(42);
URI uri = uriComponents.encode().toUri();
在上面的例子中,我們?yōu)榉椒▍?shù)準(zhǔn)備了填充值:一個long型的變量值21,以用于填充路徑變量并插入到URL中。另外,我們還提供了一個值42,以用于填充其他剩余的URI變量,比如從類層級的請求映射中繼承來的hotel
變量。如果方法還有更多的參數(shù),你可以為那些不需要參與URL構(gòu)造的變量賦予null值。一般而言,只有@PathVariable
和@RequestParam
注解的參數(shù)才與URL的構(gòu)造相關(guān)。
還有其他使用MvcUriComponentsBuilder
的方法。比如,你可以通過類似mock掉測試對象的方法,用代理來避免直接通過名字引用一個控制器方法(以下方法假設(shè)MvcUriComponentsBuilder.on
方法已經(jīng)被靜態(tài)導(dǎo)入):
UriComponents uriComponents = MvcUriComponentsBuilder
.fromMethodCall(on(BookingController.class).getBooking(21)).buildAndExpand(42);
URI uri = uriComponents.encode().toUri();
上面的代碼例子中使用了MvcUriComponentsBuilder
類的靜態(tài)方法。內(nèi)部實現(xiàn)中,它依賴于ServletUriComponentsBuilder
來從當(dāng)前請求中抽取schema、主機名、端口號、context路徑和servlet路徑,并準(zhǔn)備一個基本URL。大多數(shù)情況下它能良好工作,但有時還不行。比如,在準(zhǔn)備鏈接時,你可能在當(dāng)前請求的上下文(context)之外(比如,執(zhí)行一個準(zhǔn)備鏈接links的批處理),或你可能需要為路徑插入一個前綴(比如一個地區(qū)性前綴,它從請求中被移除,然后又重新被插入到鏈接中去)。
對于上面所提的場景,你可以使用重載過的靜態(tài)方法fromXxx
,它接收一個UriComponentsBuilder
參數(shù),然后從中獲取基本URL以便使用?;蚰阋部梢允褂靡粋€基本URL創(chuàng)建一個MvcUriComponentsBuilder
對象,然后使用實例對象的fromXxx
方法。如下面的示例:
UriComponentsBuilder base = ServletUriComponentsBuilder.fromCurrentContextPath().path("/en");
MvcUriComponentsBuilder builder = MvcUriComponentsBuilder.relativeTo(base);
builder.withMethodCall(on(BookingController.class).getBooking(21)).buildAndExpand(42);
URI uri = uriComponents.encode().toUri();
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: