In a Spring application, I have a controller with the following annotation:
@RequestMapping(value = "/{category}/", method = GET)
I'd like to have other controllers matching a single pre-defined path variable, e.g.
@RequestMapping(value = "/payment/", method = GET)
I think it is doable since I see several websites implementing this kind of URLs.
E.g. you may have several paths for the categories
http ://www.mysite.com/computer/
http ://www.mysite.com/smartphone/
http ://www.mysite.com/printer/
and then others for "static contents"
http ://www.mysite.com/payment/
http ://www.mysite.com/shopping-bag/
http ://www.mysite.com/wish-list/
Can anyone show me how to do it?
I googled a little bit and I found within the Spring docs something that I never tried. I think you could use regex into the request mapping to do the trick.
The dynamic path variables should stay as you described, i.e.
@RequestMapping(value = "/{category}/", method = GET)
public String dynamicController(@PathVariable String category){
...
}
This in theory will match all the URLs like:
protocol://localhost:8080/123/
protocol://localhost:8080/random-text/
protocol://localhost:8080/whatever-it-comes/
The static controller should be changed like this:
@RequestMapping(value = "/{accepted_path:^payment$}/", method = GET)
public String staticController(){//you don't need to consume the path
//variable accepted_path
...
}
The use of the regex ^payment$
should ensure that the URL
protocol://localhost:8080/payment/
will be binded by staticController
only.
You could also append several accepted path variables. E.g. if the staticController
must match the following URLs
protocol://localhost:8080/payment/
protocol://localhost:8080/pay/
Then you should replace "/{accepted_path:^payment$}/"
with "/{accepted_path:^payment|pay$}/"
.
Is not tested, but should do the trick!
It is doable like the way you did already. If my site is http://example.com-
@RequestMapping(value = "/test", method = RequestMethod.GET)
above code will create http://example.com/test
If I want an URI with static name and a variable (http://example.com/test/variableName) then I would use-
@RequestMapping(value = "/test/{variableName}", method = RequestMethod.GET)