Reputation: 86627
I want to create a REST-GET controller in spring-mvc
that takes a list of objects, eg 10 ids as follows:
@RestController
public class MyRest {
@RequestMapping(method = RequestMethod.GET)
public Object test(@RequestParam value="id" required=false) List<Integer> ids) {
Sysout(ids);
}
}
Anyway when I call it, I have to repeat the id param multiple times:
localhost:8080/app?id=1&id=2&id=3&...
It is possible to change the param to some kind of list? Eg
app?id=1,2,3,4,5
And if yes, is this advisable? What's better from the client point of view?
Upvotes: 5
Views: 11030
Reputation: 195
Controller :
public @ResponseBody String getInfos(HttpServletRequest request,
@RequestParam @DateTimeFormat( @RequestParam List<Long> ids) {...}
Request :
http://localhost:8080/test/api?ids=1,2,3
Upvotes: 1
Reputation: 5647
You can provide list of objects to rest service as request param.Here is the example
@RequestMapping(value = "/animals, method = RequestMethod.GET)
public void test(@RequestParam(value="animalsNames[]") String[] animalsNames) {
Sysout(animalsNames);
}
And your request looks like
http://localhost:8080/appname/animals?animalsNames[]=dog,horse
HTTP Method type : GET
Upvotes: 2
Reputation: 7646
Its better to use POST message with JSON or XML as request body. As you never know how many id's will be passed.
@RestController
public class MyRest {
@RequestMapping(method = RequestMethod.POST)
public Object test(@RequestBody IDRequest request) {
Sysout(ids);
}
public static final class IDRequest {
List<Integer> ids;
<!-- getter/setters--->
}
}
where the request will be some kind of a JSON or XML like this
{"ids":[1,2,3,4,5,6,7,8,9]}
Upvotes: 2