使用多个@GET

时间:2018-01-16 10:24:51

标签: java jax-rs

我有一个名为Book with fields genre and author的课程,我有两个单独的方法,一个是按流派获取书籍,另一个是由作者获取书籍,在我的代码中,我无法通过作者检索书籍,只能通过流派工作,可以解释一下,下面是我的代码

@GET
    @Produces({"application/xml"})
    @Consumes({"application/xml"})
    @Path("{genre}")
    public List<book> Find_Book_By_Genre(@PathParam("genre") String genre)
    {
        return  bcontl.getBookByGenre(genre);
    }

    @GET
    @Produces({"application/xml"})
    @Consumes({"application/xml"})
    @Path("{author}")
    public List<book> getBookByAuthor(@PathParam("author") String author, @Context HttpHeaders headers)
    {
        return  bcontl.getBookByAuthor(author);
    }

2 个答案:

答案 0 :(得分:2)

这两种方法都有一个通配符路径,这使得框架很难决定哪个方法应该处理请求,因此选择了第一个匹配方法。试试:

@Path("/genre/{genre}")

@Path("/author/{author}")

答案 1 :(得分:0)

您的资源方法定义对于JAX-RS来说是不明确的,它将无法正常工作。您可以考虑Jeroen's answer中描述的解决方案,但我建议您采用不同的方法。

一旦您的主要资源是图书,并且您想要过滤图书集,我建议您使用查询参数

@Path("books")
public class BookResource {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<Book> findBooks(@QueryParam("genre") String genre,
                                @QueryParam("author") String author) {
        ...
    }
}

然后您的请求将如下:

  • GET /api/books:获取所有图书的代表。

  • GET /api/books?genre=mistery:代表所有与该流派相匹配的图书。

  • GET /api/books?author=john:获取与作者匹配的所有图书的代表。

  • GET /api/books?genre=mistery&author=john:获取与该类型和作者相匹配的所有图书的代表。

如果需要,这种方法可以更容易地引入其他过滤器。