开发者

Match the "Rest of the URL" using Spring 3 RequestMapping Annotation [duplicate]

开发者 https://www.devze.com 2023-02-01 03:50 出处:网络
This question already has answers here: Closed 10 years ago. Possible Duplicate: Spring 3 RequestMapping: Get path value
This question already has answers here: Closed 10 years ago.

Possible Duplicate:

Spring 3 RequestMapping: Get path value

In Spring 3, is there a way to capture rest/of/the/url in the following URL:

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

by using a @RequestMapping annotation like this:

@RequestMapping(value="{appname}/{path1}/{path2}/{remainder}")
public String m开发者_Python百科yRequestMethod(
    @PathVariable("appname") String appName, 
    PathVariable("path1") String path1, 
    PathVariable("path2") String path2,
    PathVariable("remainder") String remainder)

I would like the RequestMapping to match like this

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

In the Javadocs for RequestMapping there is a note about using an alternate regular expression:

By default, the URI template will match against the regular expression [^.]* (i.e. any character other than period), but this can be changed by specifying another regular expression, like so: /hotels/{hotel:\d+}

But this doesn't behave as expected (I get 404) when I use a RequestMapping like so:

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

Does anyone know how to match the rest of an URL with a Spring RequestMapping?


Funny thing: I just came across the need to do this too. Here's how I solved it:

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

The "**" here says 'grab anything at any sub-path of what's to the left of me.' If you want the path it actually matched to get to this method, you can use:

request.getAttribute( HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE )

You will get /someChildUrlIfYouWant/the/full/path/to/whatever.html so if you just want the variable child path, you'll have to trim the front part of the string.

Make sense?


For the above try:

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

The default behavior of Spring to stop matching on '.' in urls is not very intuitive. I don't think period character has any special meaning in the context of the path(as opposed to say '/', ';' or '?').

0

精彩评论

暂无评论...
验证码 换一张
取 消