【发布时间】:2018-05-30 04:40:29
【问题描述】:
我正在尝试学习如何创建 RESTful Web 服务。 我正在尝试执行以下操作: 创建一个从消息列表返回消息对象(JSON 格式)的方法。 (已使用构造函数初始化)
这些 URI 正常运行:
http://localhost:8080/MyMessenger/webapi/testresource/1 http://localhost:8080/MyMessenger/webapi/testresource/2 http://localhost:8080/MyMessenger/webapi/testresource/3
对于 URI: http://localhost:8080/MyMessenger/webapi/testresource/4
我收到以下回复:
{
"id": 1,
"message": "m1"
}
但是,我在数组列表中只添加了 3 个元素。 我在这里做错了什么?
我猜这与多次运行构造函数有关。但我没有看到这种情况发生在任何地方。
@Path("testresource")
public class MessageResource {
private static List<Message> list = new ArrayList<>();
public MessageResource() {
list.add(new Message(1L,"m1"));
list.add(new Message(2L,"m2"));
list.add(new Message(3L,"m3"));
}
@GET
@Path("{messageId}")
@Produces(MediaType.APPLICATION_JSON)
public Message getSpecificMessage(@PathParam("messageId") int messageId) {
return list.get(messageId-1);
}
}
【问题讨论】: