Passing indefinite Query Parameters with RESTful U

2020-03-26 05:51发布

问题:

I have a requirement to design a RESTful Service using RESTEasy. Clients can call this common service with any number of Query Parameters they would want to. My REST code should be able to read these Query Params in some way. For example if I have a book search service, clients can make the following calls.

http://domain.com/context/rest/books/searchBook?bookName=someBookName
http://domain.com/context/rest/books/searchBook?authorName=someAuthor& pubName=somePublisher
http://domain.com/context/rest/books/searchBook?isbn=213243
http://domain.com/context/rest/books/searchBook?authorName=someAuthor

I have to write a service class like below to handle this.

@Path("/books")
   public class BookRestService{

    // this is what I currently have, I want to change this method to in-take all the 
    // dynamic parameters that can come
    @GET
    @Path("/searchBook")
    public Response searchBook(@QueryParam("bookName") String bookName,@QueryParam("isbn") String isbn) {

     // fetch all such params
     // create a search array and pass to backend

    }

    @POST
    @Path("/addBook")
    public Response addBook(......) {
    //....
     }
    }

Sorry for the bad format (I couldn't get how code formatting works in this editor!). As you can see, I need to change the method searchBook() so that it will take any number of query parameters.

I saw a similar post here, but couldn't find the right solution.

How to design a RESTful URL for search with optional parameters?

Could any one throw some light on this please?

回答1:

The best thing to do in this case would be using a DTO containing all the fields of your search criteria. For example, you mentioned 4 distinct parameters.

  1. Book Name (bookName)
  2. Author Name (authorName)
  3. Publisher Name (pubName)
  4. ISBN (isbn)

Create a DTO containing the fields having the following annotations for every property you want to map the parameters to:

public class CriteriaDTO{

  @QueryParam("isbn")
  private String isbn;
.
.

Other getter and setters of other properties

}

Here is a method doing that for your reference:

@GET
@Produces("application/json")
@Path("/searchBooks")
public ResultDTO search(@Form CriteriaDTO dto){
}

using following URL will populate the CriteriaDTO's property isbn automatically:

your.server.ip:port/URL/Mapping/searchBooks?isbn=123456789&pubName=testing



回答2:

A similar question was asked here: How do you map multiple query parameters to the fields of a bean on Jersey GET request?

I went with kensen john's answer (UriInfo) instead. It allowed to just iterate through a set to check which parameters were passed.