gpt4 book ai didi

java - 在 Jersey 中为 REST API 处理完整和部分 View

转载 作者:行者123 更新时间:2023-11-29 08:04:23 25 4
gpt4 key购买 nike

我正在为一个项目创建一个 RESTful API。我在尝试用 Jersey 实现它时遇到了一些问题:

  1. 我的对象模型显然不包含 uri 信息。例如,假设我有一个 Fruit 类。 Fruit 对象可以说是 FruitName 和 FruitColor。但在响应中我还需要发送一个 URI。这通常是如何处理的?我是否应该创建一个单独的“FruitResource”,它有一个构造函数,它接受一个“Fruit”并从中创建一个完整的资源,包括 URI?我也需要嵌套对象中的 URI,例如,如果我要返回 Child 对象列表,我需要每个 Child 对象也有一个 URI,但我不想URI 作为对象模型的一部分。最干净的方法是什么?

  2. 我希望能够返回同一资源的完整 View 和部分 View 。例如,部分 View 只有名称和 URI。如何完成这项工作?

现在我有一个接受请求的 Service 类,它使用 DAO 创建和返回对象,因为它们是从数据库建模的,序列化的使用 jackson 转换为 JSON。

最佳答案

我有一种使用 JaxB 类的方法,您可以将对象模型传递给 JaxB 类,然后 JaxB 类生成 URI。下面是小原型(prototype)。

用户资源类

@Path("/user")
public class UserResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{user-id}")
public UserJaxB getUser(@PathParam("user-id") String userId, @Context
HttpServletRequest request) {
// now XYZ is hard-coded value
String serviceEndpoint = request.getContextPath() + "/" + "user";
UserModel userModel = new UserModel(userId, "XYZ");
return new UserJaxB(serviceEndpoint,userModel);
}
}

用户 JAXB 类

@XmlRootElement
public class UserJaxB {

private String name;
private String id;
private String serviceEndpoint;
private String URI;

public UserJaxB(String serviceEndpoint, UserModel userModel) {
this.name = userModel.getName();
this.id = userModel.getId();
this.serviceEndpoint = serviceEndpoint;
}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getURI() {
return this.serviceEndpoint + "/" + id;
}
}

用户模型类 公共(public)类 UserModel {

String name;
String id;

public UserModel(String name, String id) {
this.name = name;
this.id = id;
}

public String getId() {
return id;
}


public String getName() {
return name;
}
}

关于java - 在 Jersey 中为 REST API 处理完整和部分 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12322491/

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