在Jersey中处理多个查询参数

ZKS*_*fel 38 java rest path jersey

在我正在处理的Web服务中,我需要实现一个带有查询参数的URI /stats?store=A&store=B&item=C&item=D

为了分解它,我需要能够使用查询参数来指定来自多个/所有商店的数据以及来自这些商店的多个/所有商品的数据.到目前为止,我已经能够实现一个查询参数,以便提取项目数据,但我已经迷失了如何实现更多的查询,并且似乎无法找到我之前看到的资源有了这个实现.

到目前为止,我的方法是按照我的方法进行的

@GET
@Path("stats")
public String methodImCalling(@DefaultValue("All") @QueryParam(value = "item") final String item)
{
    /**Run data using item as variable**/
    return someStringOfData
}
Run Code Online (Sandbox Code Playgroud)

这适用于一个项目,如果我没有在URI中键入参数,将返回所有数据.但是,我不确定如何处理比这更多的参数.

更新:

我已经弄清楚如何通过简单地向方法添加第二个参数来使用2个不同的参数,如下所示:

public String methodImCalling(@DefaultValue("All") @QueryParam(value = "store") final String store,
    @DefaultValue("All") @QueryParam(value = "item") final String item)
Run Code Online (Sandbox Code Playgroud)

问题仍然是如何实现相同参数的多个值.

sta*_*and 76

如果将item方法参数的类型更改String为集合,例如List<String>,您应该获得一个包含您要查找的所有值的集合.

@GET
@Path("/foo")
@Produces("text/plain")
public String methodImCalling(@DefaultValue("All") 
                              @QueryParam(value = "item") 
                              final List<String> item) {
   return "values are " + item;
}
Run Code Online (Sandbox Code Playgroud)

JAX-RS规范(第3.2节)关于@QueryParam注释说明如下:

支持以下类型:
  1. 原始类型
  2. 具有接受单个String参数的构造函数的类型.
  3. valueOf具有使用单个String参数命名的静态方法的类型.
  4. List<T>,Set<T>,或SortedSet<T>其中T满足2或3以上.

  • @Teivere:这将是`www.myurl.com/foo?item = listitem1&item = listitem2` (4认同)

小智 9

List<String> items=ui.getQueryParameters().get("item");

where ui声明为其余资源中的成员,如下所示:

@Context UriInfo ui;
Run Code Online (Sandbox Code Playgroud)

缺点是它根本没有出现在方法参数中.