0

我有两个看起来像这样的 Jersey 方法

@GET
@Path("/mine")
@Produces(MediaType.APPLICATION_JSON)
List<MyStuff> getAllMyStuff();

@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
MyStuff getMyStuff(@PathParam("id"));

在这种情况下,我可以请求 /mine 和 'getAllMyStuff',或者请求 /123 并获得正确的个人资料。但是,我有一些我想在“我的”路径上使用的可选查询参数,这样做似乎会让球衣陷入循环。当我把“我的”改成

@GET
@Path("/mine")
@Produces(MediaType.APPLICATION_JSON)
List<MyStuff> getAllMyStuff(@QueryParam("offset") int offset, @QueryParam("limit") int limit);

调用“/mine”最终会映射到 ID 为“mine”的“getMyStuff”方法。

对我来说,简单地列出这些查询参数会影响这样的映射,这似乎真的很奇怪。有没有办法解决它?

4

2 回答 2

1

事实证明,这个问题实际上与我在接口和实现中声明注释的方式有关。

我有一个接口,其方法如下:

@GET
@Path("/mine")
@Produces(MediaType.APPLICATION_JSON)
List<MyStuff> getAllMyStuff(@QueryParam("offset") int offset, @QueryParam("limit") int limit);

和像这样的实现

List getAllMyStuff(@QueryParam("offset") int offset, @QueryParam("limit") int limit);

显然,在实现方法上有任何 Jersey 注释最终会否定那些从接口“继承”的。只需将我的实现更改为

List getAllMyStuff(int offset, int limit);

已解决问题。谢谢您的帮助!

于 2013-04-29T23:24:35.730 回答
0

I believe your issue is that "mine" matches both getMyStuff and getAllMyStuff methods. To disambiguate it, you can either:

Option 1: Use "/" to refer to the collection, and "/{id}" for an individual item##

@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
List<MyStuff> getAllMyStuff(@QueryParam("offset") int offset, @QueryParam("limit") int limit);

@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
MyStuff getMyStuff(@PathParam("id"));

Option 2: Use regular expresion to scope the possible id values##

If you need to keep /mine as a path, you can further specify the valid values for an id so there is no potential for collisions.

For example, if all your id's are numeric:

@GET
@Path("/mine")
@Produces(MediaType.APPLICATION_JSON)
List<MyStuff> getAllMyStuff(@QueryParam("offset") int offset, @QueryParam("limit") int limit);

@GET
@Path("/{id: [0-9]?}")
@Produces(MediaType.APPLICATION_JSON)
MyStuff getMyStuff(@PathParam("id"));

Note: I'm not sure I got the regular expression right.

于 2013-04-29T17:35:26.370 回答