3 回答

TA貢獻(xiàn)1874條經(jīng)驗(yàn) 獲得超12個(gè)贊
您不能具有可選的路徑變量,但是可以有兩個(gè)調(diào)用相同服務(wù)代碼的控制器方法:
@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();
}

TA貢獻(xiàn)1883條經(jīng)驗(yàn) 獲得超3個(gè)贊
如果您在使用Spring 4.1和Java 8,你可以使用java.util.Optional它支持@RequestParam,@PathVariable,@RequestHeader和@MatrixVariableSpring MVC中-
@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"
}
}

TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超6個(gè)贊
眾所周知,您還可以使用@PathVariable批注注入路徑變量的Map。我不確定該功能是否在Spring 3.0中可用或是否在以后添加,但是這是解決示例的另一種方法:
@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 回答
- 0 關(guān)注
- 547 瀏覽
添加回答
舉報(bào)