【问题标题】:Getting response even though the resource shouldn't exist即使资源不应该存在也得到响应
【发布时间】: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);
    }

}

【问题讨论】:

    标签: java rest jersey


    【解决方案1】:

    列表是static。这意味着对于类的所有 个实例,列表中只有一个实例。资源类在请求范围中是默认的,这意味着为每个请求实例化一个新的。因此,每次创建一个新的时,它都会添加到同一个 static 列表中。

    如果你希望资源类是单例(只有一个),那么你可以用@Singleton注解它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-16
      • 2015-10-26
      • 2017-09-18
      • 2017-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多