Tying our JavaEE EJB into our JAX-RS web service
In the previous post, we created our EJB that contains all of our application logic. In this post, we’ll tie it to our JAX-RS service then test it out. We’ll start by opening TodoService.java and overwriting the class definition with the following code:
@Path("/") public class TodoService { @Inject TodoEJB ejb; @GET @Produces(MediaType.APPLICATION_JSON) public List<Todo> getAll() { return ejb.findAll(); } @POST @Consumes(MediaType.APPLICATION_JSON) public void create(Todo incoming) { ejb.create(incoming); } @PUT @Path("{id}") @Consumes(MediaType.APPLICATION_JSON) public void update(@PathParam("id") Long id, Todo incoming) { ejb.update(id, incoming); } @DELETE @Path("{id}") public void remove(@PathParam("id") Long id) { ejb.remove(id); } }
The @Inject annotation tells the JavaEE container to inject an instance of the interface we’re defining on the following line. After that, for each endpoint we call the corresponding method we defined in our EJB.
Go ahead and build the war file by invoking:
mvn clean package
Then copy the target/todo.war file out to WILDFLY_HOME/standalone/deployments/.
We should now be ready to test this out by invoking the REST endpoints. In order to do this, we’ll need a tool. I’ve recently switched to a Chrome App called “Advanced REST Client” or ARC for short. Whatever tool you use, start it up and issue a GET request to http://localhost:8080/todo. You should see an empty JSON array returned.

Let’s test out the create endpoint by issuing a POST request to the same URL. You’ll need to add a “Content-Type” header with “application/json” as the value, and then in the body of the request you’ll need to enter valid JSON. Example:
{"description": "Test"}
You should see a 204 returned from the server. 204 is the same as a 200 (i.e. success) except it means there’s no content returned from the server.
Next, let’s re-issue the GET http://localhost:8080/todo request again. Now you should see one entry in the JSON array that’s returned:

Now we’re going to test out the update. Issue a PUT http://localhost:8080/todo/1 with the following body content:
{"description": "Test ABC"}
This will also return a 204.
After that, re-issue the original GET request. You’ll still see a JSON array with one result returned, except the description will have been updated:

So far, so good. The final endpoint we should test is the remove. Let’s send a DELETE http://localhost:8080/todo/1 request to the server and then invoke the original GET request again. You should now see an empty JSON array.

That’s it for this post. In the next post we’ll briefly talk about CORS and make our application CORS-aware.
Source code is available here: