Spring MVC 為控制器和方法指定URI

2018-07-26 14:16 更新

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();


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

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號