gpt4 book ai didi

java - Jersey/JAX-RS 中的嵌套资源 - 如何实现 Restangular 示例

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:50:40 26 4
gpt4 key购买 nike

因此从 Rest 的角度来看可能实际上不称为嵌套资源,但我感兴趣的是如何将 Jersey 类构造为 rest 提供者,以便它可以响应链式请求。

即我对基本的/users 没问题,我对/users/123 获取特定用户没问题,但是如何分支到用户的属性..../users/123/cars,/users/123/cars/23 等

很抱歉缺少信息,但在 Angular 的 Restangular 文档中将其视为示例。

https://github.com/mgonto/restangular#production-apps-using-

restangular

// Restangular returns promises
Restangular.all('users').getList() // GET: /users
.then(function(users) {
// returns a list of users
$scope.user = users[0]; // first Restangular obj in list: { id: 123 }
})

// Later in the code...

// Restangular objects are self-aware and know how to make their own RESTful requests
$scope.user.getList('cars'); // GET: /users/123/cars

// You can also use your own custom methods on Restangular objects
$scope.user.sendMessage(); // POST: /users/123/sendMessage

// Chain methods together to easily build complex requests
$scope.user.one('messages', 123).one('from', 123).getList('unread');
// GET: /user/123/messages/123/from/123/unread

最佳答案

我认为资源定位器应该可以胜任这项工作。通常,他们将请求重新定位到能够使用它的不同资源。

在您的情况下,您将拥有一个根资源 UserResource,它将处理用户和汽车、消息的子资源 - CarsResource、MessagesResource。

根资源:

@Path("users")
class UsersResource {

// GET: /users
@GET
@Path("{id}")
public User getById(@PathParam("id") long id) {...}

@Path("{id}/cars")
public CarResource getCarResource(@PathParam("id") long userId) {
return new CarResource(uesrId);
}

@Path("{id}/sendMessage")
public MessagesResource getMessagesResourceForSend(@PathParam("id") long userId) {
return new MessagesResource(userId);
}

@Path("{id}/messages")
public MessagesResource getMessagesResourceForRead(@PathParam("id") long userId) {
return new MessagesResource(userId);
}
}

汽车和消息资源:

class CarsResource {
long userId

// GET: /users/123/cars
@GET
public Car getAllCars() {
/*retrieve all cars for user userId*/
}

// GET: /users/123/cars/3
@GET
@Path("{carId}")
public Car getById(@PathParam("carId") carId) {
/*retrieve car for id carId*/
}
}

class MessagesResource {
long userId

// POST: /users/123/sendMessage
@POST
public void sendMessage(@FormParam("content") String content) {
/*send message to user userId*/
}

// GET: /user/123/messages/123/from/123/unread
@GET
@Path("{id1}/from/{id2}/unread")
public void getUnread(@PathParam("id1") long id1, @PathParam("id2") long id2) {
/*return unread messages*/
}
}

子资源不应该在类级别上用@Path 注释,它们需要在应用程序类中注册到 JAX-RS runtinme

关于java - Jersey/JAX-RS 中的嵌套资源 - 如何实现 Restangular 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25755130/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com