Spring-MVC RequestMapping URITemplate中的可选路径变量

lao*_*han 10 java regex spring-mvc uritemplate

我有以下映射:

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

对于以下URI:

foo/a/b/c/d/e/f/g/h/bar
foo/a/bar
foo/bar
Run Code Online (Sandbox Code Playgroud)

foo映射到第一个,将bar映射到最后并且工作正常.

我想要的是将foo和bar之间的所有内容映射到单个路径参数,或者如果没有中间(如在上一个URI示例中),则为null:

@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) {}
Run Code Online (Sandbox Code Playgroud)

因为我希望像{middle:.*}那样简单,只能映射到/ foo/a/bar,或者{middle:(.*/)*},这似乎没有映射到正则表达式.

在应用正则表达式模式之前,AntPathStringMatcher是否在"/"上进行标记?(制作跨越/不可能的模式)还是有解决方案?

仅供参考,这是在春季3.1M2

这看起来类似于@RequestMapping控制器和动态URL,但我没有看到解决方案.

imx*_*ylz 14

在我的项目中,我在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);
}
Run Code Online (Sandbox Code Playgroud)

请参阅HandlerMapping.html#URI_TEMPLATE_VARIABLES_ATTRIBUTE


pea*_*ody 1

据我所知是做不到的。正如您所说,在每个斜杠处分割路径后,正则表达式将应用于路径元素,因此正则表达式永远不能匹配“/”。

您可以手动检查 url 并从请求对象中自行解析它。