Handling Multiple Query Parameters in Jersey

前端 未结 3 919
萌比男神i
萌比男神i 2020-12-08 04:30

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

相关标签:
3条回答
  • 2020-12-08 04:40

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

    where ui is declared as a member in the rest resource like so :

    @Context UriInfo ui;
    

    the downside is that it doesn't appear in the methods arguments at all.

    0 讨论(0)
  • 2020-12-08 05:01

    Some libs like axios js use the square brackets notation when sending a multi-value param request: /stats?store[]=A&store[]=B&item[]=C&item[]=D

    To handle all cases (with or without square brackets) you can add another param like this:

    public String methodImCalling(
      @QueryParam(value = "store") final List<String> store, 
      @QueryParam(value = "store[]") final List<String> storeWithBrackets, 
      @QueryParam(value = "item") final List<String> item,
      @QueryParam(value = "item[]") final List<String> itemWithBrackets) {
    ...
    }
    

    Inspecting each of the arguments checking for null.

    0 讨论(0)
  • 2020-12-08 05:04

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

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

    The following types are supported:
    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.
    0 讨论(0)
提交回复
热议问题