Is there a way to pass a list to RESTFul web service method in Jersey? Something like @PathParam("list") List list?
Hope that this will help you
import java.util.List;
@Path("/customers")
public class CustomerResource {
@GET
@Produces("application/xml")
public String getCustomers(
@QueryParam("start") int start,
@QueryParam("size") int size,
@QueryParam("orderBy") List<String> orderBy) {
// ...
}
}
Ajax call url : /customers?orderBy=name&orderBy=address&orderBy=...
I found out that the best way to send a list via POST from the client to a REST service is by using the @FormParam
.
If you add a parameter twice or more times to the form, it will result into a list on the server's side.
Using the @FormParam
means on client side you generate a com.sun.jersey.api.representation.Form
and add some form parameters like shown below. Then you add the filled form to the post like that: service.path(..) ... .post(X.class, form)
(see example code).
Example-code for the client side:
public String testMethodForList() {
Form form = new Form();
form.add("list", "first String");
form.add("list", "second String");
form.add("list", "third String");
return service
.path("bestellung")
.path("add")
.type(MediaType.APPLICATION_FORM_URLENCODED)
.accept(MediaType.TEXT_XML)
.post(String.class, form);
}
Example-Code for server side:
@POST
@Path("/test")
@Produces(MediaType.TEXT_XML)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String testMethodForList(
@FormParam("list") List<String> list {
return "The list has " + list.size() + " entries: "
+ list.get(0) + ", " + list.get(1) + ", " + list.get(2) +".";
}
The return String will be:
The list has 3 entries: first String, second String, third String.
Note:
@Consumes
on server side and .type()
on client
side have to be identical as well as @Produces
and .accept()
.
@FormParam
. In case of an object you'll have to convert it to XML
or JSON String and re-convert it on the server side. For how to convert see here.
form.add(someList)
, but this will result in a String containing the list's entries on server side. It will look like: [first String, second String, third String]
. You'd have to split the String on server side at "," and cut off the square brackets for extracting the single entiries from it.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With