我有一个类,这样注释@Path
如下:
@Path("widgets")
@Produces(MediaType.APPLICATION_XML)
public class WidgetResource {
@GET
public Response getWidgets(@QueryParam("limit"))
{
//This class returns the plural noun, a list of widgets
//...}
@GET
@Path("widget/{id}")
public Response getWidgetById(@PathParam("id") long id)
{
//This class returns a single widget by id
//...}
Run Code Online (Sandbox Code Playgroud)
当我启动测试客户端时,localhost/widgets按预期映射,但是当getWidgetById
方法映射到时localhost/widgets/widget/{id}
.这不是我想要的 - 我想拥有localhost/widgets and localhost/widget/{id}
我已经尝试@Path
在类级别省略注释,但这会阻止Jersey将此类识别为REST资源(我尝试了两者ScanningResourceConfig
并且ClassNameResourceConfig
- 无法将类加载为资源,除非@Path
在类级别存在).
我猜一个(丑陋的)解决方法是将WidgetResource
类和WidgetsResource
类之间的方法分开.我认为这是一个糟糕的解决方案,因为这两种方法在同一个类中共享资源,但我确实需要REST-ful localhost/widget
(对于单个实体)和localhost/widgets
(对于复数).
我错过了什么 - 如果我只是@Path
注释方法(我无法让它工作),我有什么办法让泽西拿起这个类作为资源类,如果不是我可以强制绝对映射(@Path(/widget/{id})
)或一些相对映射(@Path(../widget/id
) - 这些都不是现实中的工作 - 只是我所追求的类比.谢谢!
ton*_*edz 11
这部分是关于你需要的:
就个人而言,我发现你的映射很奇怪而且令人困惑.保持这样:
@Path("widgets")
@Produces(MediaType.APPLICATION_XML)
public class WidgetResource {
@GET
public Response getWidgets(@QueryParam("limit")) {
//This method returns the plural noun, a list of widgets
// it's also possible to limit the number returned by
// using a query parameter. You could easily implement
// pagination by adding further query parameters like
// 'offset', 'sortOrder', etc.
//...
}
@GET
@Path("{id}")
public Response getWidgetById(@PathParam("id") long id) {
//This method returns a single widget by id
//...
}
}
Run Code Online (Sandbox Code Playgroud)
将路径附加到具有ID的集合以从集合中获取对象似乎很自然.真的没有必要去做widgets/widget/{id}
.这widget
部分是显而易见的,没必要.
这是关于RESTful API的一个非常简洁的教程: 由apigee"教狗到REST"我认为这是一个非常好的视频.作者提出了几点好处.这是指向同一演示文稿的较长版本的链接
这部分是关于你想要的:
如果你真的想要保持复数/奇异二元论(我真的不推荐),你可以像这样注释你的代码: 但它真的很难看
@Path("/")
@Produces(MediaType.APPLICATION_XML)
public class WidgetResource {
@GET
@Path("widgets")
public Response getWidgets(@QueryParam("limit")) {
//This method returns the plural noun, a list of widgets
//...}
@GET
@Path("widget/{id}")
public Response getWidgetById(@PathParam("id") long id) {
//This method returns a single widget by id
//...
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7995 次 |
最近记录: |