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

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

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)

array as a PathVariable in Spring MVC

You cannot do that via a PathVariable, but you can pass an array via a RequestParam

Check How to pass an array within a query string? and @RequestParam array mapping issues for more info.

@PathVariable ListUUID in Spring MVC

This issue will be fixed in Spring 3.2. See https://jira.springsource.org/browse/SPR-9765 for details.

Spring controller not working when the last PathVariable in RequestMapping has only

Thanks for your responses.

But in my case the second string should be optional sometimes. I changed the second string to "RequestParam" so that the new url would be something like this /simple/test?q=something

new requestmapping would be @RequestMapping(path="/simple/test/{string1}")

so the solution code is

@RequestMapping(path = "/search/test/{string1}", produces = APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public SearchResult search( @PathVariable String string1, @RequestParam Optional<String> string2) {
if (!string2.isPresent()) {
return service.getLastQueries(string1, string2);
}
}


Related Topics



Leave a reply



Submit