我有以下映射:
@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 之间的所有内容映射到单个路径参数,如果没有中间部分则为 null(如上一个 URI 示例):
@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 是否在应用正则表达式模式之前对“/”进行标记? (使跨越/不可能的模式)或者有解决方案吗?
仅供引用,这是在 Spring 3.1M2
这看起来类似于 @RequestMapping controllers and dynamic URLs但我在那里没有看到解决方案。
最佳答案
在我的项目中,我在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);
}
关于java - Spring-MVC RequestMapping URITemplate 中的可选路径变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7841770/