2011-10-20 80 views
9

我有以下映射:可選路徑變量

@RequestMapping(value = "/{first}/**/{last}", method = RequestMethod.GET) 
public String test(@PathVariable("first") String first, @PathVariable("last") 
    String last) {} 

這對於下面的URI:

foo/a/b/c/d/e/f/g/h/bar 
foo/a/bar 
foo/bar 

映射第一酒吧最後工作正常。

我想的東西,foo和酒吧之間的映射一切都變成一個單一的路徑PARAM或null如果沒有中間(如在最後URI爲例):

@RequestMapping(value = "/{first}/{middle:[some regex here?]}/{last}", 
    method = RequestMethod.GET) 
public String test(@PathVariable("first") String first, @PathVariable("middle") 
    String middle, @PathVariable("last") String last) {} 

在美麗的卡住正則表達式,因爲我希望簡單的像{middle:。*},其中只有映射到/ foo/a/bar或{middle:(。* /)*},這似乎映射到什麼都沒有。

在應用正則表達式模式之前,AntPathStringMatcher是否在「/」上標記大小? (使模式跨越/不可能)還是有解決方案?

FYI這是在Spring 3.1M2

這似乎類似於@RequestMapping controllers and dynamic URLs,但我沒有看到一個解決方案出現。

回答

1

據我所知,無法完成。就像你所說的那樣,正則表達式在分割每個斜線處的路徑之後被應用到路徑元素,所以正則表達式不能匹配'/'。

您可以手動檢查url並從請求對象中自己解析它。

13

在我的項目重複,我使用內部變量在springframework的:

@RequestMapping(value = { "/trip/", // /trip/ 
     "/trip/{tab:doa|poa}/",// /trip/doa/,/trip/poa/ 
     "/trip/page{page:\\d+}/",// /trip/page1/ 
     "/trip/{tab:doa|poa}/page{page:\\d+}/",// /trip/doa/page1/,/trip/poa/page1/ 
     "/trip/{tab:trip|doa|poa}-place-{location}/",// /trip/trip-place-beijing/,/trip/doa-place-shanghai/,/trip/poa-place-newyork/, 
     "/trip/{tab:trip|doa|poa}-place-{location}/page{page:\\d+}/"// /trip/trip-place-beijing/page1/ 
}, method = RequestMethod.GET) 
public String tripPark(Model model, HttpServletRequest request) throws Exception { 
    int page = 1; 
    String location = ""; 
    String tab = "trip"; 
    // 
    Map pathVariables = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); 
    if (pathVariables != null) { 
     if (pathVariables.containsKey("page")) { 
      page = NumberUtils.toInt("" + pathVariables.get("page"), page); 
     } 
     if (pathVariables.containsKey("tab")) { 
      tab = "" + pathVariables.get("tab"); 
     } 
     if (pathVariables.containsKey("location")) { 
      location = "" + pathVariables.get("location"); 
     } 
    } 
    page = Math.max(1, Math.min(50, page)); 
    final int pagesize = "poa".equals(tab) ? 40 : 30; 
    return _processTripPark(location, tab, pagesize, page, model, request); 
} 

HandlerMapping.html#URI_TEMPLATE_VARIABLES_ATTRIBUTE

-1

嘗試使用此

@RequestMapping(value = {"some mapped address","some mapped address with path variable","some mapped address with another path variable"}) 

特定於可用網址的數組列表方法

但是,當您在方法簽名中使用@PathVariable時,請注意創建url列表,它不能爲null。

希望得到這個幫助