12.07.2015 Views

Beginning Java EE 6 with GlassFish 3, Second Edition

Beginning Java EE 6 with GlassFish 3, Second Edition

Beginning Java EE 6 with GlassFish 3, Second Edition

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 15 ■ RESTFUL WEB SERVICESThe JAX-RS ModelFrom Listing 15-2, you can see that the REST service doesn’t implement any interface nor extend anyclass; the only mandatory annotation to turn a POJO into a REST service is @Path. JAX-RS relies onconfiguration by exception, so it has a set of annotations to configure the default behavior. Following arethe requirements to write a REST service:• The class must be annotated <strong>with</strong> @javax.ws.rs.Path.• To add EJB capabilities to a REST service, the class has to be annotated <strong>with</strong>@javax.ejb.Stateless.• The class must be defined as public, and it must not be final or abstract.• Root resource classes (classes <strong>with</strong> a @Path annotation) must have a default publicconstructor. Non-root resource classes do not require such a constructor.• The class must not define the finalize() method.JAX-RS is HTTP-centric by nature and has a set of clearly defined classes and annotations to deal<strong>with</strong> HTTP and URIs. A resource can have several representations, so the API provides support for avariety of content types and uses JAXB to marshall and unmarshall XML and JSON representationsfrom/into objects. JAX-RS is also independent of the container, so resources can be deployed in<strong>GlassFish</strong>, of course, but also in a variety of servlet containers.How to Write a REST ServiceListing 15-2 shows how to write a very simple REST service. But most of the time you need to access adatabase, retrieve or store data in a transactional manner. You can have stateless session beansfunctionalities on REST services, by adding the @Stateless annotation allowing transactional access to apersistent layer (JPA entities), as shown in Listing 15-3.Listing 15-3. A Book Resource Creating and Retrieving Books from the Database@Path("books")@Stateless@Produces({"application/xml", "application/json"})@Consumes({"application/xml", "application/json"})public class BookResource {@Contextprivate UriInfo uriInfo;@PersistenceContext(unitName = "chapter15PU")private EntityManager em;464

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!