10

我有以下映射:

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

对于以下 URI 来说:

foo/a/b/c/d/e/f/g/h/bar
foo/a/bar
foo/bar

将foo映射到first并将bar映射到last并且工作正常。

我想要的是将 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) {}

非常卡在正则表达式上,因为我希望像 {middle:.*} 这样简单的东西,它只映射到 /foo/a/bar,或者 {middle:(.*/)*},它似乎什么都没有映射。

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

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

这似乎类似于@RequestMapping 控制器和动态 URL,但我在那里没有看到解决方案。

4

4 回答 4

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

请参阅HandlerMapping.html#URI_TEMPLATE_VARIABLES_ATTRIBUTE

于 2013-05-24T09:45:19.167 回答
1

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

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

于 2012-05-16T17:01:38.930 回答
1

这可以通过编写自定义路径匹配器并配置 Spring 来使用它来完成。例如,这样的解决方案记录在这里:http: //java.dzone.com/articles/spring-3-webmvc-optional-path

该链接提供了一个自定义路径匹配器,并展示了如何配置 spring 以使用它。如果您不介意编写自定义组件,那应该可以解决您的需求。

另外,这是与 Spring 3.0 的副本,我可以制作一个可选的路径变量吗?

于 2012-11-19T19:44:52.283 回答
-1

尝试使用这个

@RequestMapping(value = {"some mapped address","some mapped address with path variable","some mapped address with another path variable"})

特定方法的可用 url 的数组列表

但是,当您在方法签名中使用 @PathVariable 时,创建 url 列表时要小心,它不能为空。

希望这有帮助

于 2014-09-15T07:11:55.920 回答