Java Reference
In-Depth Information
IMPLEMENTING REST IN JAVA EE
This chapter has discussed at length the theory behind a well‐designed RESTful API.
Now that you have seen how you might style the URIs, you can jump in and see how all this looks
in code.
Java EE 7 provides some helpful annotations that make the job of constructing a RESTful API
straightforward. The most useful is the @Path annotation. This annotation dei nes the context
URI and the class or method that will process requests made on that URI. Additionally, there are
annotations for each HTTP method: @GET , @POST , @PUT , @DELETE , and so on. These annotations
mark methods that will process requests made with the stated HTTP method.
Your application can have more than one RESTful context. To take care of this case, the
@ApplicationPath annotation takes a parameter that denotes the space in which your RESTful API
will exist. With just these two types of annotations, you have all you need to implement a simple
RESTful API.
Now in Listing 13‐1 you'll implement the URI GET /users .
LISTING 13‐1: Simplest implementation of a RESTful API in Java EE
package co.uk.devchronicles.forum;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Application;
@ApplicationPath("/")
@Path("users")
public class Users extends Application{
@GET
public String getUsers(){
return "Here we return a representation of all users";
}
}
If you have this application deployed on your local machine and your application is called
forum , you can test this URI by visiting http://localhost/forum/users . Y ou should notice
the text message Here we return a representation of all users displayed in the browser
window.
Note in Listing 13‐1 how you can annotate the class with the @Path annotation and pass it the
users context. The string that you pass does not have to be preceded by a forward slash or be
followed by a trailing slash. The space in which the RESTful interface will exist has been dei ned as
the root ("/") of the application. The method that is called when a GET request is made to the URI
users is annotated with the @GET annotation. In this simple example, a string is returned, but the
real goal is to send back the data retrieved for the database in a JSON or XML format along with
an HTTP status code. This is what occurs in Listing 13‐2.
 
Search WWH ::




Custom Search