【问题标题】:Match the "Rest of the URL" using Spring 3 RequestMapping Annotation [duplicate]使用 Spring 3 RequestMapping Annotation 匹配“URL 的其余部分”[重复]
【发布时间】:2011-05-31 08:38:22
【问题描述】:

可能重复:
Spring 3 RequestMapping: Get path value

在 Spring 3 中,有没有办法在以下 URL 中捕获rest/of/the/url

/myapp/foo/bar/rest/of/the/url

通过使用像这样的@RequestMapping 注释:

@RequestMapping(value="{appname}/{path1}/{path2}/{remainder}")
public String myRequestMethod(
    @PathVariable("appname") String appName, 
    PathVariable("path1") String path1, 
    PathVariable("path2") String path2,
    PathVariable("remainder") String remainder)

我希望 RequestMapping 像这样匹配

{appname}   -> myapp
{path1}     -> foo
{path2}     -> bar
{remainder} -> rest/of/the/url 

在 RequestMapping 的 Javadocs 中有一条关于使用替代正则表达式的说明:

默认情况下,URI 模板将匹配正则表达式 [^.]*(即除句点之外的任何字符),但这可以通过指定另一个正则表达式来更改,例如:/hotels/{hotel:\ d+}

但是当我像这样使用 RequestMapping 时,这并没有达到预期的效果(我得到 404):

@RequestMapping(value="{appname}/{path1}/{path2}/{remainder:.[\\S]*}")

有人知道如何将 URL 的其余部分与 Spring RequestMapping 匹配吗?

【问题讨论】:

  • 你说得对。这是重复的。
  • 是的,但我更喜欢这个问题的措辞。

标签: java spring-mvc


【解决方案1】:

有趣的是:我刚刚也遇到了这样做的需要。以下是我的解决方法:

@RequestMapping(value = {"/someChildUrlIfYouWant/**"}

这里的"**" 表示“在我左边的任何子路径上抓取任何东西。”如果您希望它实际匹配的路径可以到达此方法,您可以使用:

request.getAttribute( HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE )

你会得到/someChildUrlIfYouWant/the/full/path/to/whatever.html,所以如果你只想要变量子路径,你必须修剪字符串的前面部分。

有意义吗?

【讨论】:

  • 我也是这样做的,可惜没有更好的选择,因为如果您更改端点名称,它将不再起作用
【解决方案2】:

对于上述尝试:

@RequestMapping(value="{appname}/{path1}/{path2}/{remainder:.+}")

Spring 在 '.' 上停止匹配的默认行为在 urls 中不是很直观。我认为句点字符在路径的上下文中没有任何特殊含义(与说“/”、“;”或“?”相反)。

【讨论】:

  • 嘿,这与我想要的非常接近,但它并没有像我预期的那样工作。如果我要请求 url someappname/apath/anotherpath/whatever.file 我 would 能够检索其余路径变量 aswhatever.file 但是,如果我要请求 someappname/apath/anotherpath/ and/an/other/path/whatever.file 你提供的模式 (.+) 不匹配,当我认为我会得到值和/an/other/path/whatever.file 你或其他人可以吗阅读此建议我应该使用哪种模式来获取 url 余数?
  • @RequestMapping("{appname}/{path1}/{path2}/{remainder:.*}")
  • @dgeske 它不起作用。
  • 你应该使用stackoverflow.com/a/11248730/190713。这行得通。
  • 这只对我有用,如果其余部分不包含任何斜杠。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-10
  • 1970-01-01
  • 1970-01-01
  • 2017-01-24
  • 1970-01-01
  • 2015-04-14
相关资源
最近更新 更多