在 Jersey 中处理多个查询参数 [英] Handling Multiple Query Parameters in Jersey

查看:30
本文介绍了在 Jersey 中处理多个查询参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我正在处理的 Web 服务中,我需要使用类似于 /stats?store=A&store=B&item=C&item=D 的查询参数来实现 URI

In the web service I'm working on, I need to implement a URI with query parameters which look like /stats?store=A&store=B&item=C&item=D

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

To break it down, I need to be able to use query parameters to specify data from multiple/all stores and data for multiple/all items from those stores. So far I have been able to implement one query argument just fine in order to pull item data, but I'm lost as far as to how to implement more queries, and can't seem to find the resources I had seen before which deal with this implementation.

到目前为止我的方法是沿着

What I have so far in my method is along the lines of

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

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

which works well for one item, and will return all data if I don't type the parameter in the URI. However, I am unsure how to handle any more parameters than this.

更新:

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

I have figured out how to use 2 different parameters by simply adding a second argument to the method like so:

public String methodImCalling(@DefaultValue("All") @QueryParam(value = "store") final String store,
    @DefaultValue("All") @QueryParam(value = "item") final String item)

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

The question remains of how to implement multiple values of the same parameter.

推荐答案

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

If you change the type of your item method parameter from String to a collection such as List<String>, you should get a collection that holds all the values you are looking for.

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

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

The JAX-RS specification (section 3.2) says the following regarding the @QueryParam annotation:

支持以下类型:
  1. 原始类型
  2. 具有接受单个 String 参数的构造函数的类型.
  3. 具有名为 valueOf 的静态方法和单个 String 参数的类型.
  4. ListSetSortedSet 其中 T 满足以上 2 或 3.
  1. Primitive Types
  2. Types that have a constructor that accepts a single String argument.
  3. Types that have a static method named valueOf with a single String argument.
  4. List<T>, Set<T>, or SortedSet<T> where T satisfies 2 or 3 above.

这篇关于在 Jersey 中处理多个查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆