Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring RequestMapping: differentiate PathVariable with different types

Is there a way to tell Spring to map request to different method by the type of path variable, if they are in the same place of the uri?
For example,

@RequestMapping("/path/{foo}")  

@RequestMapping("/path/{id}")

if foo is supposed to be string, id is int, is it possible to map correctly instead of looking into the request URI?

like image 271
hsluo Avatar asked Sep 24 '13 17:09

hsluo


People also ask

What is difference between @PathParam and @PathVariable?

@PathParam: it is used to inject the value of named URI path parameters that were defined in @Path expression. @Pathvariable: This annotation is used to handle template variables in the request URI mapping ,and used them as method parameters.

What is difference between PathVariable and RequestParam?

1) The @RequestParam is used to extract query parameters while @PathVariable is used to extract data right from the URI.

What is the difference between @path and @RequestMapping?

The @PathVariable annotation is used for data passed in the URI (e.g. RESTful web services) while @RequestParam is used to extract the data found in query parameters. These annotations can be mixed together inside the same controller.

Can we use both PathVariable and RequestParam?

@RequestParam and @PathVariable can both be used to extract values from the request URI, but they are a bit different.


1 Answers

According to the spring docs it is possible to use regex for path variables, here's the example from the docs:

@RequestMapping("/spring-web/{symbolicName:[a-z-]+}-{version:\\d\\.\\d\\.\\d}{extension:\\.[a-z]+}")
  public void handle(@PathVariable String version, @PathVariable String extension) {
    // ...
  }
}

(example taken from http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping-patterns )

Judging from that, it should be possible to write something like this for your situation:

@RequestMapping("/path/{foo:[a-z]+}")  

@RequestMapping("/path/{id:[0-9]+}")
like image 115
Krešimir Nesek Avatar answered Nov 15 '22 16:11

Krešimir Nesek