Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass List to RESTful webservice

Tags:

java

jersey

Is there a way to pass a list to RESTFul web service method in Jersey? Something like @PathParam("list") List list?

like image 511
Jason Avatar asked Jul 05 '10 20:07

Jason


2 Answers

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=...

like image 83
Yogesh Prajapati Avatar answered Oct 15 '22 06:10

Yogesh Prajapati


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 @Consumes on server side and .type() on client side have to be identical as well as @Produces and .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.
like image 2
Jana Avatar answered Oct 15 '22 07:10

Jana