2011-02-04 59 views
140

使用Spring 3.0,我可以有一個可選的路徑變量嗎?使用Spring 3.0,我可以創建一個可選的路徑變量嗎?

例如

@RequestMapping(value = "/json/{type}", method = RequestMethod.GET) 
public @ResponseBody TestBean testAjax(
     HttpServletRequest req, 
     @PathVariable String type, 
     @RequestParam("track") String track) { 
    return new TestBean(); 
} 

這裏想/json/abc/json到調用相同的方法。
一個明顯的解決方法聲明type作爲一個請求參數:

@RequestMapping(value = "/json", method = RequestMethod.GET) 
public @ResponseBody TestBean testAjax(
     HttpServletRequest req, 
     @RequestParam(value = "type", required = false) String type, 
     @RequestParam("track") String track) { 
    return new TestBean(); 
} 

然後/json?type=abc&track=aa/json?track=rr將工作

回答

147

你不能有可選的路徑變量,但你可以有兩個控制器方法調用其中的相同服務代碼:

@RequestMapping(value = "/json/{type}", method = RequestMethod.GET) 
public @ResponseBody TestBean typedTestBean(
     HttpServletRequest req, 
     @PathVariable String type, 
     @RequestParam("track") String track) { 
    return getTestBean(type); 
} 

@RequestMapping(value = "/json", method = RequestMethod.GET) 
public @ResponseBody TestBean testBean(
     HttpServletRequest req, 
     @RequestParam("track") String track) { 
    return getTestBean(); 
} 
+0

這無疑是做的一個很好的方式。 – Shamik 2011-02-05 01:48:00

+3

@Shamik:在我看來,這是一個引人注目的理由*不*使用路徑變量。組合增殖可能很快失去控制。 – skaffman 2011-02-05 11:40:13

+7

其實並不是因爲路徑不夠複雜,而是充滿了可選組件。如果您有多個或最多兩個可選路徑元素,則應認真考慮將其中的一些切換爲請求參數。 – 2012-04-23 10:44:40

20

你可以使用:

@RequestParam(value="somvalue",required=false) 

可選PARAMS而非pathVariable

69

不知道你也可以使用@PathVariable註解來注入路徑變量的Map。我不知道是否可以使用該功能在Spring 3.0,或者如果它是後來添加的,但這裏是另一種方式來解決這個例子:如果您使用Spring 4.1和Java 8你

@RequestMapping(value={ "/json/{type}", "/json" }, method=RequestMethod.GET) 
public @ResponseBody TestBean typedTestBean(
    @PathVariable Map<String, String> pathVariables, 
    @RequestParam("track") String track) { 

    if (pathVariables.containsKey("type")) { 
     return new TestBean(pathVariables.get("type")); 
    } else { 
     return new TestBean(); 
    } 
} 
-3
$.ajax({ 
      type : 'GET', 
      url : '${pageContext.request.contextPath}/order/lastOrder', 
      data : {partyId : partyId, orderId :orderId}, 
      success : function(data, textStatus, jqXHR) }); 

@RequestMapping(value = "/lastOrder", method=RequestMethod.GET) 
public @ResponseBody OrderBean lastOrderDetail(@RequestParam(value="partyId") Long partyId,@RequestParam(value="orderId",required=false) Long orderId,Model m) {} 
67

可以在Spring MVC使用java.util.Optional這是在@RequestParam支持,@PathVariable@RequestHeader@MatrixVariable -

@RequestMapping(value = {"/json/{type}", "/json" }, method = RequestMethod.GET) 
public @ResponseBody TestBean typedTestBean(
    @PathVariable Optional<String> type, 
    @RequestParam("track") String track) {  
    if (type.isPresent()) { 
     //type.get() will return type value 
     //corresponds to path "/json/{type}" 
    } else { 
     //corresponds to path "/json" 
    }  
} 
相關問題