Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring and several controllers matching a single path variable

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?

like image 663
mat_boy Avatar asked Jun 07 '26 15:06

mat_boy


1 Answers

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!

like image 95
JeanValjean Avatar answered Jun 09 '26 03:06

JeanValjean



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!