问题
Is there a way to pass a list to RESTFul web service method in Jersey? Something like @PathParam("list") List list?
回答1:
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 @FormParammeans 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:
- The MediaTypes of
@Consumeson server side and.type()on client side have to be identical as well as@Producesand.accept(). - You can NOT send objects other than String, Integer etc. via
@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. - You can also pass a List to the form like
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.
回答2:
Hope that this will help you
Java code
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) {
// ...
}
}
Passing value from javascript using AJAX
Ajax call url : /customers?orderBy=name&orderBy=address&orderBy=...
回答3:
If I'm understanding what you're trying to do, you could serialize the List object and pass it as a string.
来源:https://stackoverflow.com/questions/3182033/pass-list-to-restful-webservice