簡體   English   中英

獲取URI路徑中的變量

[英]Get the variable in the path of a URI

在Spring MVC中,我有一個控制器,可以監聽所有進入/my/app/path/controller/*請求。

假設請求來到/my/app/path/controller/blah/blah/blah/1/2/3

如何獲取/blah/blah/blah/1/2/3部分,即與處理程序映射定義中的*匹配的部分。

換句話說,我正在尋找類似於pathInfo為servlet做的事情,但是對於控制器。

在Spring 3中,您可以使用@ PathVariable注釋來獲取URL的部分內容。

以下是http://blog.springsource.com/2009/03/08/rest-in-spring-3-mvc/的簡單示例

@RequestMapping(value="/hotels/{hotel}/bookings/{booking}", method=RequestMethod.GET)
public String getBooking(@PathVariable("hotel") long hotelId, @PathVariable("booking") long bookingId, Model model) {
    Hotel hotel = hotelService.getHotel(hotelId);
    Booking booking = hotel.getBooking(bookingId);
    model.addAttribute("booking", booking);
    return "booking";
}

在Spring 2.5中,您可以覆蓋任何將HttpServletRequest實例作為參數的方法。

org.springframework.web.servlet.mvc.AbstractController.handleRequest

在Spring 3中,您可以向控制器方法添加HttpServletRequest參數,spring將自動將請求綁定到它。 例如

    @RequestMapping(method = RequestMethod.GET)
    public ModelMap doSomething( HttpServletRequest request) { ... }

在任何一種情況下,此對象都與您在servlet中使用的請求對象相同,包括getPathInfo方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM