将列表传递给RESTful Web服务

有没有办法将列表传递给Jersey中的RESTFul Web服务方法? 像@PathParam(“list”)列表一样的东西?

希望这对你有所帮助

Java代码

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 orderBy) { // ... } } 

使用AJAX从javascript传递值

Ajax调用url: /customers?orderBy=name&orderBy=address&orderBy=...

我发现通过POST从客户端向REST服务发送列表的最佳方法是使用@FormParam
如果向表单添加两次或更多次参数,它将导致服务器端的列表。

在客户端使用@FormParam意味着生成一个com.sun.jersey.api.representation.Form并添加一些表单参数,如下所示。 然后将填充的表单添加到post中: service.path(..) ... .post(X.class, form) (请参阅示例代码)。

客户端的示例代码:

 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); } 

示例 – 服务器端代码:

 @POST @Path("/test") @Produces(MediaType.TEXT_XML) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public String testMethodForList( @FormParam("list") List list { return "The list has " + list.size() + " entries: " + list.get(0) + ", " + list.get(1) + ", " + list.get(2) +"."; } 

返回String将是:

该列表有3个条目:第一个String,第二个String,第三个String。

注意:

  • 服务器端的@Consumes和客户端的.type()的MediaTypes必须与@Produces.accept()

  • 您不能通过@FormParam发送String,Integer等以外的对象。 如果是对象,则必须将其转换为XML或JSON String,并在服务器端重新转换它。 如何转换请看这里

  • 您还可以将List传递给form.add(someList)类的表单,但这将导致包含服务器端列表条目的String。 它看起来像: [first String, second String, third String] 。 您必须将服务器端的String拆分为“,”并切掉方括号以从中提取单个entiries。

如果我理解你要做什么,你可以序列化List对象并将其作为字符串传递。