gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:53:02 30 4
gpt4 key购买 nike

我有以下映射:

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

参见 HandlerMapping.html#URI_TEMPLATE_VARIABLES_ATTRIBUTE

关于java - Spring-MVC RequestMapping URITemplate 中的可选路径变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7841770/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com