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 myRequestMethod(
@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?
One of the most important annotations in spring is the @RequestMapping Annotation which is used to map HTTP requests to handler methods of MVC and REST controllers. In Spring MVC applications, the DispatcherServlet (Front Controller) is responsible for routing incoming HTTP requests to handler methods of controllers.
The @GetMapping annotation assigns specified handler methods to HTTP GET requests. @RequestMapping(method = RequestMethod. GET) is a constructed annotation that serves as a shorthand for @RequestMapping(method = RequestMethod.
In case of @RestController the parameter value depicts the component name or bean name, whereas in @RequestMapping the value parameter is used to specify the path. Both are used for different purpose. If you want to specify request URI path on controller class name use @RequestMapping annotation with @RestController .
From the naming convention we can see that each annotation is meant to handle respective incoming request method type, i.e. @GetMapping is used to handle GET type of request method, @PostMapping is used to handle POST type of request method, etc.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With