REST with Jersey and Jetty part 3
Adding JSON support.
The first two parts in this small series of posts were about setting up the server and be able to run it with Jersey. [REST with Jersey and Jetty part 1, REST with Jersey and Jetty part 2].This time there will be a bit more work. And I will take it step by step.
The service we will implement will handle tasks. To start with, there will only be one task list where all tasks will go.
The api will be the following.
Task class:
To start with we add support for getting the list, there will be some hardcoding until we have the working JSON support, since the first thing we want is a working Jersey with JSON support, not to complicate things further. When we have that, we can start adding functionality. But in the end, we will try to support:
- list all
- show a single task
- create a task
- update a task
- remove a task
- show range of tasks
- get task count
But starting with some hardcoded stuff, to get the server running with JSON, this will be the stating point for the TaskResource
If you start the server and try to surf to this [http://localhost:2001/api/tasks] will yield the following in the log.
so we need to add some stuff to have JSON support.
Well, just a shor Googling, and it was pretty easy to add. [http://stackoverflow.com/questions/25474223/jersey-rest-messagebodywriter-not-found-for-media-type-application-jso] gives a hint. Just added moxy and it works to get JSON with the @GET.
So lets go for some real coding. We will add a simple cache, To avoid having a database for this simple example it will only contain a map with the tasks.
Lets start with some simple support of the cache:
Lets first add a method to create a task and one for getting a specific task.
To test this, we will need to also add a method to get a single task and a client to test it.
First, the client.
So far the client just adds a Task, gets the URI to the created Task and then gets it using the @GET for the methods added above.
Next step, fix the getAll().
The client cannot handle a List without wrapping it in a GenericType, but that is really all there is too it, we can still return List
The only thing we need to add now is update and delete. We will also add some code to test it in the client.
I also made some changes in the client:
Enjoy your Task microservice in REST using embedded Jetty with Jersey.
Read more about Jersey [https://jersey.java.net/documentation/latest/index.html]
No comments:
Post a Comment