0

I need to implement a controller for processing requests whith filter use Jersey framework. For example:

.../myservice/book - display a list of all books.

.../myservice/book?chapter=1,5 - display 1 and 5 books chapters.

.../myservice/book?page=10,50 - display 10 and 50 books pages.

.../myservice/book?chapter=1,5&page=10,50 - display 1 and 5 books chapters and only 10 and 50 book pages.

I can't use .../myservice/book/chapter/1,5/page/10,50, because possible situation: .../myservice/book/7 - display book 7 and filters described above can be applied here. Is it possible to implement it in this way?:

public class TestController {

@Path("/book")
@GET
public Object getBook() {
    // return a list of all books
}

public Object getBook(@QueryParam("chapter") String chapter) {
    // return books chapters    
}

public Object getBook(@QueryParam("page") String page) {
    // return books pages   
}

public Object getBook(@QueryParam("chapter") String page, @QueryParam("page") String page) {
    //  return books chapters and pages
    }
}

Or to add all kinds of filters in one method and verify the presence of a large number of conditions?

4

1 回答 1

0

您不能将相同的路径映射到多个资源方法。您要么必须提供单独的路径,要么使用单一方法。我会选择后者,然后委托给其他辅助方法:

@Path("/book")
@GET
public Object getBooks(@QueryParam("chapter") String chapter, @QueryParam("page") String page) {
    if (chapter == null && page == null)
      return getAllBooks();
    else if (chapter == null)
      return getBooksByPages(...);
    else if (page == null)
      return getBooksByChapters(...);
    else
      return getBooksByPagesAndChapters(...);
}

旁注:您可以使用多个查询参数,而不是将您的页面和章节作为逗号分隔的字符串传递:.../myservice/book?chapter=1&chapter=5并且 Jersey 会为您将它们放入一个列表中:@QueryParam("chapter") List<String> chapters

于 2013-09-30T00:40:22.653 回答