This page last changed on Jul 24, 2012 by 17555.

With the advent of Java EE 5, Enterprise Beans can act as Web-Service components and since Java EE 6 they may be packaged within a WAR module as Java programming language class files. Java EE based web services come in two flavours: JAX-WS and JAX-RS. This tutorial examines JAX-RS and EJB 3.1.


Java API for RESTful Web Services (JAX-RS) is the Java EE6 standard for creating RESTful Web Services according to the Representational State Transfer (REST) architectural principals. REST has no standard and is just a style of architecture with design criteria that can be implemented by several languages. Jersey, the reference implementation of JAX-RS included in GlassFish distributions, makes it easy for developers to build RESTful web services by using the Java programming language. This tutorial  demonstrates how to create a JAX-RS application based on  stateless session EJBs with GlassFish Server and Eclipse for Java EE developers. A sample application is provided too.

Downloading, Installing, and Configuring Required Software

Before you begin, download, install, and configure the required software.

  1. Ensure that Java Development Kit (JDK) 6 is installed and that paths and environment variables for the JDK are correct. If the JDK and the Java Runtime Environment (JRE) are installed, ensure that the path to the JDK precedes the path to the JRE in your path statement. Otherwise, GlassFish Server might use a JRE for its Java virtual machine (VM) and steps for compiling JavaServer Pages (JSP) technology pages will fail.
  2. Download and install Eclipse IDE for Java EE developers.
  3. Download and install GlassFish Server Open Source Edition 3.1.2.
  4. Download and install the GlassFish Server plugin for Eclipse IDE. When you add an update site, specify the location as http://download.java.net/glassfish/eclipse/indigo and not the location that is stated in the instructions.
  5. Register your installation of GlassFish Server with Eclipse IDE. When you select the server type, select GlassFish 3.1.2 and not the type that is stated in the instructions.
  6. Change the global preferences for GlassFish Server to meet the requirements of your application. If your application uses the Java DB database that is bundled with GlassFish , select all options on the Preferences page as shown in the following figure. Cannot resolve external resource into attachment.

Setting Up the Database and Data Source

Exactly how to set up the database and data source depends on the database that your application uses. For detailed instructions, see Administering Database Connectivity in Oracle GlassFish Server Administration Guide.

Modifying the DerbyPool Connection Pool

The sample application uses the preconfigured DerbyPool connection pool for connections to the database. To enable the sample application to use this pool, you must modify the preset values of some properties of the pool.

Before you begin, ensure that the option to start the Java DB process with GlassFish Server is set in the global preferences for the GlassFish Server.

  1. Start GlassFish Server in Eclipse IDE. The JavaDB database that is bundled with GlassFish Server is also started.
  2. In the Servers view, select and right-click GlassFish Server.
  3. From the pop-up menu that opens, choose GlassFish→View Admin Console. The GlassFish Server Administration Console is opened in the system browser.
  4. In the navigation tree, under the Resources node, expand the JDBC node.
  5. Under the JDBC node, select the JDBC Connection Pools node. The Connection Pools page opens.
  6. In the table of connection pools, click DerbyPool. The Edit Connection Pool page opens.
  7. On the Edit Connection Pool page, click the Additional Properties tab. The Edit Connection Pool Properties page opens.
  8. Edit the properties as follows:
    Property Value
    User user
    Password user
    DatabaseName newdb

    The following figure shows the Edit Connection Pool Properties page after these properties have been edited. Cannot resolve external resource into attachment.

  9. Click Save.
  10. Confirm that the connection to the pool is usable.
    1. On the Edit Connection Pool Properties page, click the General tab. The Edit Connection Pool page opens.
    2. On the Edit Connection Pool page, click Ping.
  11. Confirm that the JNDI name of the connection pool is correct.
    1. In the navigation tree, under the Resources node, expand the JDBC node.
    2. Under the JDBC node, select the JDBC Resources node. The JDBC Resources page opens.

On the JDBC Resources page, select jdbc/__default. DerbyPool is associated with this JNDI name as shown in the following figure. Cannot resolve external resource into attachment.

Sample Application overview

The sample application consists of two parts: a "server" application (web service provider) and a "client" application (web service consumer).

  • The client application allows an end-user to enter the name of a customer. It's a simple form that invokes a basic servlet to process the data. The web tier accesses a session bean which implements the business logic (adding an application specific id to the customer). The session bean also acts as a web service consumer sending the Customer Object (with the @XMLRootElement  annotation which allows JAXB to convert this entity from Java to XML and back) to the server.
  • The server application is a session bean which receives the XML representation of the Customer Object and saves it to a RDBMS using a Java persistence entity. The entity accesses the database table that store the entity states. A plain old Java object (the Customer Object) with some annotations specifies how JPA is to store the data persistently.

You can read more about the JAX-RS standard at jax-rs.java.net , about the JPA standard at Java EE6 tutorial, about the JAXB standard at jaxb.java.net.

To Convert the Sample Application to an Eclipse IDE Project

The sample application is distributed as a two web application archive (WAR) files. To use this applications, you must convert them to Eclipse IDE projects.

  1. Download the server and the client application WAR file (ServerRS-web.war and ClientRS-web.war).
  2. Import the application WAR files into Eclipse IDE.  

The server application

As of new EE6 specifications, stateless, stateful and singleton session beans can be used as web service provider. An EJB no longer requires a local business interface: it may expose a no-interface view. EJB's packaging has changed too. Enterprise beans, often providing the business logic of a web application or in this case of a web service, may be packaged within a WAR module as Java programming language class files or within a JAR file that is bundled within the WAR module.

  1. Even with EJBs, this is a dynamic web project in Eclipse.
  2. In the source folder of this project, there's a META-INF directory with the persistence.xml file. The application uses the JavaDB database, with Glassfish Server. By default, GlassFish Server Open Source Edition uses EclipseLink as the persistence provider and it controls transactions by using the using the jdbc/_default DataSource object. This object is specified in the jta-data-source element of the persistence.xml file as follows:                  
    <jta-data-source>jdbc/__default</jta-data-source>
  3. A small entry in the web.xml deployment descriptor is required to map Jersey REST Service.  
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
      <display-name>ServerRS-web</display-name>
      <servlet>
        <servlet-name>Jersey REST Service</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <load-on-startup>1</load-on-startup>
      </servlet>
      <servlet-mapping>
        <servlet-name>Jersey REST Service</servlet-name>
        <url-pattern>/rest/*</url-pattern>
      </servlet-mapping>
    </web-app>
  4. No WSDL file is associated with a JAX-RS service, there's a Web Application Description Language WADL file (an XML-based file format that provides a machine-readable description of the RESTFul web service) available at "http://localhost:8080/ServerRS-web/rest/application.wadl".
  5. The @LocalBean annotation denotes a no-interface ejb and the class, a stateless session bean, also needs to be decorated with the @Stateless annotation.The @Path("ee.entity.customer") annotation indicates the path of the resource (the URL used to access it). In this case, it’s something like "http://localhost:8080/ServerRS-web/rest/ee.entity.customer". The @Produces and @Consumes annotations define the default content type that this resource produces or consumes: XML. You can override this content type on a per-method basis.   
    @Stateless
    @LocalBean
    @Path("ee.entity.customer")
    public class CustomerServiceBean {
        @PersistenceContext(unitName = "CustomerService")
        private EntityManager em;
    
        @POST
        @Consumes(MediaType.APPLICATION_XML)
        public void createCustomer(Customer customer) {
        	  em.persist(customer);
    	 }
    
    	@GET
        @Produces(MediaType.APPLICATION_XML)
        @Path("findAllCustomers")
    	@SuppressWarnings("unchecked")
         public List<Customer> findAllCustomers() {
            Query query = em.createNamedQuery("findAllCustomers");
            List<Customer> customers=query.getResultList();
            for( Customer cust:customers ){
          	   if (cust.getFirstName().equals(""))
            	throw new WebApplicationException(Response.status(500).entity("There is a customer on the database without a name!").build());
         	  }
           return customers;
        }
    
    }
  6. The Customer object represents the XML content of the XML message and acts as an entity too. Typically an entity represents a table in a relational database, and each entity instance corresponds to a row in that table. This java class is converted to an XML format by JAXB. JAXB provides the ability to marshal Java objects into XML and the inverse. When a top level class is annotated with the @XmlRootElement annotation, then its value is represented as XML element in an XML document
    @Entity
    @XmlRootElement
    @NamedQuery(name = "findAllCustomers", query = "SELECT b FROM Customer b")
    
    public class Customer implements java.io.Serializable {
    	private static final long serialVersionUID = 1L;
    	@Id
        @GeneratedValue(strategy=GenerationType.IDENTITY)
        private Long id;
    
        private String firstName;
    
        private String lastName;
    
        private Long appCode;
    
        public Long getId() {	return id;	}
    	public void setId(Long id) {this.id = id;	}
    
    	public Long getAppCode() {return appCode;	}
    	public void setAppCode(Long appCode) {this.appCode = appCode;}
    
    	public String getFirstName() { return firstName; }
        public void setFirstName(String firstName) { this.firstName = firstName; }
    
        public String getLastName() { return lastName; }
        public void setLastName(String lastName) { this.lastName = lastName; }
    
        @Override
    	public String toString() {
    		return "Customer [id=" + id + ", firstName=" + firstName
    				+ ", lastName=" + lastName + ", appCode=" + appCode + "]";
    	}
    }

To Run the Server Application

  1. In the Project Explorer view, select and right-click the ServerRS-web project.
  2. From the pop-up menu that opens, select Run As→Run on Server. The Run on Server wizard opens.
  3. Ensure that the option to choose an existing server is selected.
  4. From the list of servers, select GlassFish Server and click Next. The Add and Remove page opens.
  5. Confirm that ServerRS-web is listed under the configured projects.
  6. Click Finish.

The client application

  1. To consume HTTP-based RESTful Web Services exposed by the server application, the client application relies on Jersey client API (included in GlassFish distributions).
  2. To start working with the Jersey client API, you need to create an instance of the com.sun.jersey.api.client.Client class.
  3. The client application retrieves the Collection of Customer objects through the use of the GenericType. The GenericType class deals with type erase that happens in generic collections at run time. Jersey intercepts the request and wraps the Generic collection with their GenericType.
    @Stateless
    @LocalBean
    public class ClientEjbBean {
    
       private static final String BASE_URI = "http://localhost:8080/ServerRS-web/ee.entity.customer";
    
     //business method
     // it adds a business code to the customer
       public void sendCustomer(Customer customer){
    	   customer.setAppCode(new Long(1234567));
    	   Client.create().resource(BASE_URI).type(javax.ws.rs.core.MediaType.APPLICATION_XML).post(customer);
       }
    
       public List<Customer> findAllCustomers(){
    	   List<Customer> customers = Client.create().resource(BASE_URI).path("findAllCustomers").accept(MediaType.APPLICATION_XML).get(new GenericType<List<Customer>>(){});
    	   return customers;
       }
    
    }
  4. There's no validation on the insert form of the client application: to raise a checked exception on the server side just insert a blank first name.
  5. Exceptions thrown by a resource class method are caught by the JAX-RS runtime and converted by default to a 500 Server Error response. Methods can throw WebApplicationException which can contain a customized Response or the application can include a bundled exception mapping provider which will be called to create a customized Response when an exception is caught. In the ServerRS-Web application the Exception Message is available to the client at "http://localhost:8080/ServerRS-web/rest/ee.entity.customer/findAllCustomers" which is the URI of the method throwing the Exception.
  6. To run the client application, follow the same steps as the server application.

Further Reading

For more information about the technologies in this tutorial, see the following documentation:


xmlerrorscreen.jpg (image/jpeg)
Document exported from wikis.oracle.com on May 27, 2015 20:43
Copyright © 2005-2015 Oracle and/or its affiliates. All rights reserved.