99re热这里只有精品视频,7777色鬼xxxx欧美色妇,国产成人精品一区二三区在线观看,内射爽无广熟女亚洲,精品人妻av一区二区三区

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

2018-07-26 14:16 更新

Spring MVC也提供了構(gòu)造指定控制器方法鏈接的機(jī)制。以下面代碼為例子,假設(shè)我們有這樣一個(gè)控制器:

@Controller
@RequestMapping("/hotels/{hotel}")
public class BookingController {

    @RequestMapping("/bookings/{booking}")
    public String getBooking(@PathVariable Long booking) {

    // ...

    }
}

你可以通過引用方法名字的辦法來準(zhǔn)備一個(gè)鏈接:

UriComponents uriComponents = MvcUriComponentsBuilder
    .fromMethodName(BookingController.class, "getBooking", 21).buildAndExpand(42);

URI uri = uriComponents.encode().toUri();

在上面的例子中,我們?yōu)榉椒▍?shù)準(zhǔn)備了填充值:一個(gè)long型的變量值21,以用于填充路徑變量并插入到URL中。另外,我們還提供了一個(gè)值42,以用于填充其他剩余的URI變量,比如從類層級(jí)的請(qǐng)求映射中繼承來的hotel變量。如果方法還有更多的參數(shù),你可以為那些不需要參與URL構(gòu)造的變量賦予null值。一般而言,只有@PathVariable@RequestParam注解的參數(shù)才與URL的構(gòu)造相關(guān)。

還有其他使用MvcUriComponentsBuilder的方法。比如,你可以通過類似mock掉測(cè)試對(duì)象的方法,用代理來避免直接通過名字引用一個(gè)控制器方法(以下方法假設(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)部實(shí)現(xiàn)中,它依賴于ServletUriComponentsBuilder來從當(dāng)前請(qǐng)求中抽取schema、主機(jī)名、端口號(hào)、context路徑和servlet路徑,并準(zhǔn)備一個(gè)基本URL。大多數(shù)情況下它能良好工作,但有時(shí)還不行。比如,在準(zhǔn)備鏈接時(shí),你可能在當(dāng)前請(qǐng)求的上下文(context)之外(比如,執(zhí)行一個(gè)準(zhǔn)備鏈接links的批處理),或你可能需要為路徑插入一個(gè)前綴(比如一個(gè)地區(qū)性前綴,它從請(qǐng)求中被移除,然后又重新被插入到鏈接中去)。

對(duì)于上面所提的場(chǎng)景,你可以使用重載過的靜態(tài)方法fromXxx,它接收一個(gè)UriComponentsBuilder參數(shù),然后從中獲取基本URL以便使用?;蚰阋部梢允褂靡粋€(gè)基本URL創(chuàng)建一個(gè)MvcUriComponentsBuilder對(duì)象,然后使用實(shí)例對(duì)象的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)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

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

編程獅公眾號(hào)