Pass List to RESTful webservice

梦想的初衷 提交于 2019-12-05 10:38:23
Jana

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.
Yogesh Prajapati

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

If I'm understanding what you're trying to do, you could serialize the List object and pass it as a string.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!