Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an Array or List to @Pathvariable - Spring/Java

I am doing a simple 'get' in JBoss/Spring. I want the client to pass me an array of integers in the url. How do I set that up on the server? And show should the client send the message?

This is what I have right now.

@RequestMapping(value="/test/{firstNameIds}", method=RequestMethod.GET) @ResponseBody public String test(@PathVariable List<Integer> firstNameIds) {      //What do I do??      return "Dummy";  } 

On the client I would like to pass something like

 http://localhost:8080/public/test/[1,3,4,50] 

When I did that I get an error:

java.lang.IllegalStateException: Could not find @PathVariable [firstNameIds] in @RequestMapping

like image 920
Djokovic Avatar asked Mar 08 '12 18:03

Djokovic


People also ask

What is the use of @PathVariable annotation in Spring rest?

The @PathVariable annotation is used to extract the value of the template variables and assign their value to a method variable. A Spring controller method to process above example is shown below; @RequestMapping("/users/{userid}", method=RequestMethod.

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.

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.


2 Answers

GET http://localhost:8080/public/test/1,2,3,4  @RequestMapping(value="/test/{firstNameIds}", method=RequestMethod.GET) @ResponseBody public String test(@PathVariable String[] firstNameIds) {     // firstNameIds: [1,2,3,4]     return "Dummy";  } 

(tested with Spring MVC 4.0.1)

like image 148
atamanroman Avatar answered Sep 18 '22 05:09

atamanroman


You should do something like this:

Call:

GET http://localhost:8080/public/test/1,2,3,4

Your controller:

@RequestMapping(value="/test/{firstNameIds}", method=RequestMethod.GET) @ResponseBody public String test(@PathVariable List<Integer> firstNameIds) {      //Example: pring your params      for(Integer param : firstNameIds) {         System.out.println("id: " + param);      }      return "Dummy"; } 
like image 27
Bruno Conrado Santos Avatar answered Sep 20 '22 05:09

Bruno Conrado Santos