0

I am trying to learn how to create RESTful web services. I am trying to do the following: Create a method that returns a Message Object (in JSON format) from a list of Messages. (Which has been initialized using constructor)

It runs normally for these URIs:

http://localhost:8080/MyMessenger/webapi/testresource/1 http://localhost:8080/MyMessenger/webapi/testresource/2 http://localhost:8080/MyMessenger/webapi/testresource/3

For URI: http://localhost:8080/MyMessenger/webapi/testresource/4

I get the following response:

{
    "id": 1,
    "message": "m1"
}

But, I have added only 3 elements in the arraylist. What am I doing wrong here?

I am guessing it has something to do with running the constructor multiple times. But I don't see that happening anywhere.

@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);
    }

}
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
Gaurav Kumar
  • 136
  • 8

1 Answers1

2

The list is static. This means that there is only one instance of the list for all instances of the class. The resource class is be default in a request scope, meaning a new one is instantiated for each request. So every time a new one is created, it is adding to the same static list.

If you want the resource class to be a singleton (only one), then you can annotate it with @Singleton.

Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720