在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调用相同的方法。 一个明显的解决方法是将类型声明为请求参数:

@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 or /json?Track =rr将工作


当前回答

Nicolai Ehmann的评论和wildloop的回答的简化示例(适用于Spring 4.3.3+),基本上你现在可以使用required = false:

  @RequestMapping(value = {"/json/{type}", "/json" }, method = RequestMethod.GET)
  public @ResponseBody TestBean testAjax(@PathVariable(required = false) String type) {
    if (type != null) {
      // ...
    }
    return new TestBean();
  }

其他回答

你不能有可选的路径变量,但你可以有两个控制器方法调用相同的服务代码:

@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();
}

如果你正在使用Spring 4.1和Java 8,你可以使用Java .util. optional,它在Spring MVC -中的@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"
    }       
}

你可以使用a:

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

用于可选参数而不是pathVariable

Nicolai Ehmann的评论和wildloop的回答的简化示例(适用于Spring 4.3.3+),基本上你现在可以使用required = false:

  @RequestMapping(value = {"/json/{type}", "/json" }, method = RequestMethod.GET)
  public @ResponseBody TestBean testAjax(@PathVariable(required = false) String type) {
    if (type != null) {
      // ...
    }
    return new TestBean();
  }

检查这个Spring 3 WebMVC -可选路径变量。它展示了一篇对AntPathMatcher进行扩展以启用可选路径变量的文章,可能会有帮助。这篇文章都要归功于塞巴斯蒂安·赫罗尔德。