Home arrow Java & J2EE arrow Page 11 - Using RPC-Style Web Services with J2EE

Exposing EJBs Through Web Service Protocols - Java

Web Services provide functionality to the Internet, and are seen as the wave of the future. In this article, Martin Bond explains how to use Web Services protocols to join J2EE application components with any other software that supports those protocols. This excerpt is from Chapter (Day) 20, from Teach Yourself J2EE in 21 Days, second edition, by Martin Bond, et. al. (Sams, 2003, ISBN: 0672325586)

  1. Using RPC-Style Web Services with J2EE
  2. Web Service Overview
  3. Web Service Technologies and Protocols
  4. Web Services for J2EE
  5. RPC-Oriented Web Services
  6. Creating a Simple Service
  7. The WSDL File
  8. Creating the Web Service WAR
  9. The Web Services Deployment Descriptor
  10. Building More Robust Web Services
  11. Exposing EJBs Through Web Service Protocols
  12. Web Service Compiler Configuration File
  13. Configuring the EJB Component
  14. Other Considerations for Web Services
  15. Summary
By: Sams Publishing
Rating: starstarstarstarstar / 13
December 08, 2004

print this article



The types of application functionality exposed through Web Service protocols will be many and varied. The variety of such applications will match, if not exceed, the variety of browser-based applications found on the Web. This means that Web Service applications will have a variety of requirements for such systemic qualities as scalability, availability, performance, and so on. Essentially, Web Service applications are just like any other application. Because of their requirements for scalability and availability, the functionality behind many Java-based Web Services will be implemented using EJBs. What is needed then is a simple way to expose this functionality while keeping overhead to the minimum.

EJBs as Web Service Facades

On Day 18, the role of the facade pattern was discussed as a way of reducing network traffic and creating a simpler, coarse-grained interface from a set of fine-grained interfaces. The use of a Session Facade providing coarse-grained access to entity EJBs has been particularly successful.

As Web Services are intended to be a coarse-grained interface to underlying functionality, the Facade pattern also applies at a Web Service boundary. Indeed, an overarching Session Facade may contain the coarse-grained representation of the business logic implemented by combinations of entity and session EJBs in the application. This overarching Session Facade is ideal to be exposed using Web Service protocols—indeed it may have been created for just such a purpose.

You will now examine an example that uses a stateless session EJB as a Façade for some of the agency functionality from the case study. The façade will provide a list of jobs available at a given location. The stateless session bean will call on underlying entity beans to retrieve the required data. The client will be a standalone Java client just as for the servlet-based Web Service implementation.

Defining the Interface and Implementation

JAX-RPC allows you to expose a stateless session bean so that it can be accessed through Web Service protocols. In developer terms, the main difference between an EJB exposed through JAX-RPC and one exposed through RMI is that you do not provide the same interface files. For an RMI-based EJB, you will provide a home interface and an EJB business interface that extends javax.ejb.EJBObject or javax.ejb.EJBLocalObject. An EJB developed to be exposed as a Web Service does not have a home interface. The relationship between the client and server is different and the client delegates all lookup of services to the proxy as you saw in the GreetingClient class earlier. Similarly, the business interface is defined slightly differently to reflect the different relationship. While the interface for a Web Service EJB is still a Remote interface, it must directly extend java.rmi.Remote rather than one of the EJBObject variants.

Note - As it stands, you cannot use the same interface definition for the EJB Remote interface and the Web Service using the tools provided with the J2EE RI (wscompile will generate an error if your Web Service interface extends javax.ejb.EJBObject rather than java.rmi.Remote). This can be seen as a good thing, as it might tempt people to always specify the EJB remote interface as a Web Service interface for the associated EJB. You should not just automatically expose all stateless session EJBs as Web Services. However, if you have a well-crafted, coarse-grained facade implemented as a stateless session EJB, there is no reason you should not expose this as a Web Service.

Listing 20.8 shows an interface that can be used to expose an EJB method that lists the job vacancies registered with the job agency at a particular location. You can see that the interface extends Remote and the findJobsAtLocation() method is labeled as throwing RemoteException. The interface defines a single method that takes a location as a string and returns a string array of job information. Nothing much indicates that this interface is part of an EJB.

Listing 20.8 A Web Service Interface for Agency Functionality (Service.java)

package agency;
import java.rmi.*;
public interface Service extends Remote
public String[] findJobsAtLocation(String location) throws 
RemoteException; }

The implementation, on the other hand, looks like a typical session EJB as shown in listing 20.9. Examination of the code reveals that it has the usual lifecycle methods for a stateless session bean and retrieves the local resources it needs in its setSessionContext() method. The only resource it uses is a reference to the home interface of the entity Job EJB.

The bean implements the single business method—findJobsAtLocation()—defined on the Service interface. The implementation of this method uses the findByLocation method on the JobHome interface which returns a list of the jobs at the given location. The method creates a Job EJB instance for each job in the list and calls the getCustomer() and getRef() methods on its JobLocal interface. The strings created from the job information are stored in an array to be returned to the caller.

Listing 20.9 An Enterprise Bean to Underpin a Web Service (ServiceBean.java)

package agency;
import java.util.*;
import java.rmi.*;
import javax.ejb.*;
import javax.naming.* ;
import data.*;
public class ServiceBean implements SessionBean
private JobLocalHome jobHome;
public String[] findJobsAtLocation(String location)
String[] jobs = null;
Collection col = jobHome.findByLocation(location);
jobs = new String[col.size()];
Iterator it=col.iterator();
for (int i=0; i < jobs.length; ++i)
JobLocal job = (JobLocal)it.next();
jobs[i] = job.getCustomer() + "/" + job.getRef();
catch (Exception ex)
// In response to any error just return null
jobs = null;
return jobs;
// EJB methods start here
public void ejbCreate () throws CreateException {}
public void ejbActivate(){}
public void ejbPassivate(){}
public void ejbRemove(){}
private SessionContext ctx;
public void setSessionContext(SessionContext ctx)
this.ctx = ctx;
InitialContext ic = null;
ic = new InitialContext();     
jobHome = (JobLocalHome)ic.lookup("java:comp/env/ejb/JobLocal");
catch (NamingException ex)
error("Error looking up java:comp/env/ejb/JobLocal",ex);
private void error (String msg, Exception ex)
String s = "ServiceBean: "+msg + "\n" + ex;
throw new EJBException(s,ex);

The only real difference between this bean implementation and any other stateless session bean is that exceptions are treated differently. When it is exposed through a native RMI interface, the bean implementor can assume that the caller has some way of dealing with any exceptions thrown by the bean, so any errors can be raised as exceptions. However, in Web Service terms, you are less certain how an exception will appear to a client and so it is safer to adopt a less Java-specific stance. In this case, an error is indicated by a null return value. The handling of errors and exceptions in Web Services is discussed later in the section "Web Service Errors and Exceptions."

This chapteris fromTeach Yourself J2EE in 21 Days, second edition, byMartin Bond et. al.(Sams, 2004, ISBN: 0-672-32558-6). Check it out at your favorite bookstore today. Buy this book now.

>>> More Java & J2EE Articles          >>> More By Sams Publishing

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- More Java Bugs Lead to More Attacks
- Oracle's Java One Brings News, Surprises
- Oracle Patches Java Runtime Environment
- Apple Syncs Java Update with Oracle
- Spring 3.1 Java Development Framework Compat...
- Jelastic Java PaaS Availability and Pricing ...
- NetBeans 7.1 Released, Supports JavaFX 2
- SolarWinds Releases Newest Version of Java M...
- Free Monitoring Tool for Java Apps on Heroku
- Heroku Adds JCloud Platform Support, Java 7 ...
- Java SE 8 Speculation in Full Swing
- Java SE 7 Now Available
- New JVM Language and Java Reporting Tool
- Java 7 Release Update and New Eclipse Toolkit
- The Best Java Netbeans IDE Plugins

Developer Shed Affiliates


Dev Shed Tutorial Topics: