3 回答
TA贡献1874条经验 获得超12个赞
您不能具有可选的路径变量,但是可以有两个调用相同服务代码的控制器方法:
@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贡献1883条经验 获得超3个赞
如果您在使用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贡献1797条经验 获得超6个赞
众所周知,您还可以使用@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 关注
- 523 浏览
添加回答
举报