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