从URL解析路径变量
问题描述:
我必须实现与Spring PathVariable几乎类似的系统。我知道如何分析我自己的网址定义:从URL解析路径变量
定义:
blog-{String}-{Integer}
代码:
Pattern p = Pattern.compile("\\{.+?\\}");
Matcher m = p.matcher(pathFormat);
while(m.find())
{
String group = m.group();
// ...
}
但我怎么能解析与我的格式,真实的URL?如果真正的URL像
blog-my-first-blogging-10001
真实网址没有括号,所以我该如何使用正则表达式来匹配我的组。组的类型是已知的,但没有括号如何匹配?
答
也许有点傻,但为什么不尝试:
String restOfPath = pathFormat.substring(5); //eliminate 'blog-' prefix
int lastDash = restOfPath.lastIndexOf('-'); //find the last '-'
String title = restOfPath.substring(0, lastDash); // take what's before '-'
String id = restOfPath.substring(lastDash + 1); // take the rest.
?
除非你的路径可以比blog-{String}-{Integer}
更复杂,否则这里不需要regex。
答
目前尚不清楚(至少对我来说)你正在尝试做的,这里是我如何使用弹簧路径变量:
@RequestMapping(value = "/{MyBlog}/{myVar}", method = RequestMethod.GET)
public ModelAndView getBlog(@PathVariable final String MyBlog, @PathVariable final Integer myVar) {
final ModelAndView mav = new ModelAndView(MyBlog);
mav.addObject("myVar", myVar);
// in actuality do lots of other thigns
return mav;
}
而且,它还将使用url http://myApp.com/AnyBlogName/21
,其中21可以是任何访问数字和AnyblogName可以是你想要的字符串。
Thanx输入,但我需要几乎可以匹配任何可能的网址,就像Spring PathVariable通用的解决方案... – newbie 2012-02-17 09:17:20
@newbie你有问题是,你正在捕获的字符串可以包含路径分隔符。 AFAIK春天和所有的URI模板的实现可能会bork,如果你试图匹配'word/a/lot/of/words/anotherword'对'word/{something/anotherword'(即它不匹配)。这是你的情况,只能用破折号而不用斜杠。 – soulcheck 2012-02-17 09:24:31
糟糕,没错,url模板必须有分隔符才能工作,我错过了。 – newbie 2012-02-17 09:26:25