如何将 varargs 传递给 @GET 请求
How can I pass varargs to a @GET request
我正在尝试设置一项服务,允许使用它从数据库中检索多个条目。为了允许用户指定他们想要查看的条目,我为 ID 号传递了可变参数:
public Person getPersons(int... ids) {
//my code here
}
不过,我如何设置它以使用@QueryParam 或@FormParam?我试过这样设置:
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/search")
public Person getPersons(@QueryParam("id") int... ids) {
//my code here
}
因此,如果参数中包含 ID 号 1 和 5,则将返回这些特定配置文件的条目。
不过,这只是ids变量的错误,注意以下几点:
Checks types of parameters annotated @PathParam, @QueryParam, etc. The type of the annotated parameter, field or property must either:
Be a primitive type.
Have a constructor that accepts a single String argument.
Have a static method named valueOf or fromString that accepts a single String argument (see, for example, Integer.valueOf(String)).
Have a registered implementation of ParamConverterProvider JAX-RS extension SPI that returns a ParamConverter instance capable of a "from string" conversion for the type.
Be List<T>, Set<T> or SortedSet<T>, where T satisfies 2, 3 or 4 above. The resulting collection is read-only.
您需要使用不同的值多次传递相同的查询参数
id=1&id=2&id=3
然后您可以读取数组中的 ID 列表:
public Response receiveListOfID(@QueryParam("id") final List<String> idList) {
....
}
我正在尝试设置一项服务,允许使用它从数据库中检索多个条目。为了允许用户指定他们想要查看的条目,我为 ID 号传递了可变参数:
public Person getPersons(int... ids) {
//my code here
}
不过,我如何设置它以使用@QueryParam 或@FormParam?我试过这样设置:
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/search")
public Person getPersons(@QueryParam("id") int... ids) {
//my code here
}
因此,如果参数中包含 ID 号 1 和 5,则将返回这些特定配置文件的条目。
不过,这只是ids变量的错误,注意以下几点:
Checks types of parameters annotated @PathParam, @QueryParam, etc. The type of the annotated parameter, field or property must either:
Be a primitive type.
Have a constructor that accepts a single String argument.
Have a static method named valueOf or fromString that accepts a single String argument (see, for example, Integer.valueOf(String)).
Have a registered implementation of ParamConverterProvider JAX-RS extension SPI that returns a ParamConverter instance capable of a "from string" conversion for the type.
Be List<T>, Set<T> or SortedSet<T>, where T satisfies 2, 3 or 4 above. The resulting collection is read-only.
您需要使用不同的值多次传递相同的查询参数
id=1&id=2&id=3
然后您可以读取数组中的 ID 列表:
public Response receiveListOfID(@QueryParam("id") final List<String> idList) {
....
}