Java Development News:

Making your J2EE Application Web Services ready - The XML Business Delegate Pattern

By Paulo Caroli

01 Dec 2002 |


Web services has emerged as a new technology and you want to be ready for it. Currently you are a great EJB developer and have been comfortably developing EJB based applications. You have become acquainted with important terms and concepts in J2EE: the EJB Layer, Stateful and Stateless Session Beans, BMP (Bean Managed Persistence) and CMP (Container Managed Persistence) Entity Beans, DAO (Data Access Object), Value Objects, and the Service Locator. This list grows the more you read about J2EE. You wonder how far you are from Web services. This article shows how you can combine the Business Delegate, the Session Facade, the DTO (Data transfer Object) and XML to build a simple structure to make your EJB application Web services ready.

Figure 1 illustrates a combination of the Business Delegate, the Session Faacadeade and the DTO J2EE Design Patterns. The following sections will explore each part of this combination using an online banking application as our sample project.

Figure 1 - J2EE Design Patterns Combination

DTO (Data Transfer Object)

A DTO (Data Transfer Object)[1] is used to exchange data between logical components; it is especially useful when using a remote service such as EJB remote calls. DTO usage avoids expensive fine-grained network communication. A DTO is basically a plain Java Bean class that contains the data that flows between different layers in the application.

The DTO, Transfer Object and Value Object are all similar, and have been used extensively by the J2EE community. A Value Object usually represents an immutable Java Bean object (get methods only) extracted from an Entity Bean through a getValueObject() method call, while the DTO is more generically used to refer to a Java Bean object holding data transferred through remote calls. The Transfer Object is used to describe the DTO used by business components that are either a Session Bean, an Entity Bean or a DAO (Data Access Object). This article uses the DTO to refer these data holder objects.

Figure 2 shows AccountHistory and AccountHistoryContext, two DTOs used to develop our sample application.

Figure 2 - DTO Sample

Later sections detail the Client and the BankSystemEJB, but for now, let's understand these two sample DTOs. AccountHistoryContext has the data identifying the history to be returned (ex: dateFrom, dateTo, accountNumber), while AccountHistory has the data for the history to be presented (ex: transactions).

It usually makes sense to design the DTO around the needs of a particular client, Figure 3 and Figure 4 respectively show AccountHistoryContext and AccountHistory class diagrams and their matching User Interface for the sample bank-online application.

Figure 3 - AccountHistoryContext DTO sample

Figure 4 - AccountHistory DTO sample

At a glance, the DTO encapsulates a set of parameters that one component sends or returns to another component to complete a single remote method call, such as the getAccountHistory method in a BankSystem EJB. The fields in a DTO are usually fairly simple. They are primitives, simple classes like strings and dates, or other DTOs.

For more information the DTO, check out chapter 2 of EJB Design Patterns by Floyd Marinescu [1].

Session Facade

The Session facade[1][3] is one of the most common EJB patterns being employed. It is a very simple notion resulting from the application of the Facade pattern [2] into EJB development.

The Gang of Four Design Patterns book [2] describes the Facade pattern as "a unified interface to a set of interfaces in a subsystem. It defines a higher-level interface that makes the subsystem easier to use."; Sun, in 2001, [3] specialized the Facade pattern for the J2EE platform as the Session Facade core J2EE Pattern. It recommends that you "use a session bean as a facade to encapsulate the complexity of interactions between the business objects participating in a workflow. The Session Facade manages the business objects, and provides a uniform coarse-grained service access layer to clients."

Figure 5 shows the class diagram representing the Session Facade pattern.

Figure 5 - Session Facade class diagram

The EJB Layer is composed of Business objects, which are session beans, entity beans and DAOs (Data Access Objects). Working as an entry-point to the EJB Layer, the SessionFacade is a session bean that manages the relationships between numerous BusinessObjects to provide higher-level abstraction to the client.

By employing the SessionFacade, the client is provided with a coarse-grained way to access the EJB Layer. The client uses the SessionFacade instead of dealing with more fine grained components from the EJB Layer.

In summary, the SessionFacade provides a simpler interface to the clients by hiding all the complex interactions between business components. The SessionFacade reduces the number of business objects that are exposed to the client across the service layer over the network. The SessionFacade also prevents the exposure of the underlying business objects directly to the client, keeping the client and the EJB layer loosely coupled.

Going back to our sample bank online application, the sequence diagram in Figure 6 shows a possible design for the transfer operation realized by the Bank System SessionFacade. Note how the client is provided with a simple method, transfer(), without dealing directly with EntityBeans and the inherent logic for the transfer operation.

Figure 6 - Transfer Operation

Combining the Session Facade and DTO

Java requires you to have a single return value for a method call; the DTO is a meaningful, unique return type for a SessionFacade method call. DTOs should also be used as the parameter(s) for the SessionFacade methods. By having the DTOs encapsulate input and output values for the services provided by the EJB Layer, the client is supplied with an application specific vocabulary instead of Java specific words (ex: instead of get ArrayList for these String(s) and int, you have the bank system session Facade, and getAccountHistory for this accountHistoryContext)

The following sequence diagram in Figure 7 shows the combination of the SessionFacade and DTOs for the getAccountHistory operation in the bank online application.

Figure 7 - getAccountHistory operation

The Business Delegate

Sun [3] defines the BusinessDelegate as a core J2EE pattern: "Use a Business Delegate to reduce coupling between presentation-tier clients and business services. The Business Delegate hides the underlying implementation details of the business service, such as lookup and access details of the EJB architecture."

The Business Delegate exposes an interface that provides clients with access to the underlying services provided by the EJB Layer, thereby hiding these services' details.

By introducing the BusinessDelegate between the client and the Session Facade, the underlying implementation details of the business services are not exposed to the client. This makes the application more maintainable and extensible through a looser coupling between the presentation layer and the EJB Layer. As a consequence, when the implementation of the business services change, the exposed implementation code in the presentation tier might not change.

The Business Delegate is also responsible for converting service level exceptions into application level exceptions, shielding clients from knowledge of the underlying implementation-specific details. The BusinessDelegate might intercept an exception such as a java.rmi.Remote exception and then generate an application level exception instead.

Combining the Business Delegate and Session Facade

The relationships between the client, the BusinessDelegate and the SessionFacade are depicted in Figure 8. Note that the client is transparent to naming, lookup services and EJB invocation.

Figure 8 - Business Delegate class diagram

The Business Delegate can make use of the EJBHomeFactory [1] to cache the remote references to the Session Facade bean's home to improve performance by reducing the number of lookups. The Business Delegate may additionally cache any necessary data being reused in consecutive invocations.

The EJBHomeFactory pattern [1] locates EJB Homes for clients and thus abstracts the complexity of network operation and EJB Home lookup. The EJBHomeFactory hides the lookup process's implementation details and complexity from clients. To improve application performance, EJBHomeFactory caches home objects to eliminate unnecessary JNDI (Java Naming and Directory Interface) activity that occurs in a lookup operation.

DTO as an XML document

In order render the app Web services capable, the Business Delegate must receive and return information as XML document. But the EJB Layer doesn't manipulate XML data; instead, it receives and returns information as DTO objects. This section shows you how to represent a DTO object as an XML document and vice-versa, so you can combine the DTO, the SessionFacade and the BusinessDelegate, enabling XML communication with the client.

A DTO class, besides having get/set methods to expose its properties, can provide methods to help with the business logic such as methods to validate data or format values. As a Java class, the DTO is well integrated with EJB development and can make use of distinct Java APIs to accomplish specific development needs. Because of that, you should keep the data encapsulated in DTO objects while working in the EJB Layer and only convert it to and from XML documents outside the EJB Layer.

Listing 3 below shows a AccountHistoryContext XML sample (such XML is extracted from the sample user interface in Figure 3).

Note:You can download all the code presented in this article at

Listing 3:Account History Context XML representation

<?xml version="1.0" encoding="ISO-8859-1"?>
    <holder>Paulo Caroli</holder>
  <dateTo>Monday, March 11, 2002 </dateTo>
  <dateFrom>Monday, February 25, 2002 </dateFrom>

The XML representation for the AccountHistoryContext has to be converted to an AccountHistoryContext DTO object. The AccountHistoryContext DTO class provides a fromXML(String xml) method that creates and populates the DTO object matching the received XML string. This method basically parses the received XML and maps it to existing properties of the DTO. Listing 4 shows the AccountHistoryContext DTO class with its fromXML(String xml) method.

Listing 4: AccountHistoryContext DTO class

public class AccountHistoryContext
        implements InXML,{
    private String dateFrom;
    private String dateTo;
    private Account account;
    public AccountHistoryContext(){}
    public AccountHistoryContext(
        String adateFrom,
        String adateTo,
        Account aaccount)   {
    dateFrom = adateFrom;
    dateTo = adateTo;
    account = aaccount;
    public String getDateFrom(){
      return dateFrom;
    public void setDateFrom(String s){
        dateFrom = s;
    public String getDateTo(){
        return dateTo;
    public void setDateTo(String s){
        dateTo = s;
    public Account getAccount(){
        return account;
    public void setAccount(Account o){
        account = o;
    public Object fromXML(String xml){
        return (AccountHistoryContext)

Listing 5 below shows an AccountHistory XML sample document (such XML is used to populate the user interface at Figure 4).

Listing 5: Account History XML representation

<?xml version="1.0" encoding="ISO-8859-1"?>
      <withdraw>-$1,150.00 </withdraw>
      <date>3/10/2002 </date>
      <description>Check Number: 213 </description>
      <description>ATM Withdrawal 350 SAN JOSE CA</description>
      <deposit>$4,060.40 </deposit>
      <description>ACH DEPOSIT - JAVAWORLD LTD </description>
      <description>JC'S BBQ AND DELI SAN JOSE CA </description>
      <holder>Paulo Caroli</holder>
    <dateTo>Monday, March 11, 2002 </dateTo>
    <dateFrom>Monday, February 25, 2002 </dateFrom>

The XML string for the AccountHistory is produced by an AccountHistory DTO object. The AccountHistory DTO class provides a toXML() method that generates the XML string matching the DTO object. This method basically navigates the DTO properties and maps it to XML tags and values. Listing 6 shows the AccountHistory DTO class with its toXML() method.

Listing 6: AccountHistory class

public class AccountHistory
        implements OutXML,{
   private TransactionList transactionList;
   private AccountHistoryContext accountHistoryContext;

   public AccountHistory(String test){
    transactionList = new TransactionList("test");
    accountHistoryContext = new AccountHistoryContext("test");

   public AccountHistory(
          TransactionList atransactionList,
          AccountHistoryContext aaccountHistoryContext) {
    transactionList = atransactionList;
    accountHistoryContext = aaccountHistoryContext;

    public TransactionList getTransactionList(){
        return transactionList;

    public AccountHistoryContext getAccountHistoryContext(){
        return accountHistoryContext;

    public String toXML(){
      return BeanXMLMapping.toXML(this);

Listing 4 and Listing 6 present two DTO classes containing, respectively, a fromXML() and a toXML() method. In the sample code, a BeanXMLMapping component has been used for implementing the DTO-XML mapping.

The BeanXMLMapping component converts matching JavaBean and XML documents. This implementation of BeanXMLMapping uses the JOX (Java Objects in XML) library, which deals with the conversion between XML documents and JavaBeans. The BeanXMLMapping has two methods: String toXML(Object bean), whichgenerates the respective XML Document String for the bean instance, and Object fromXML(String xml), which creates a bean instance for the XML Document String.

To learn more about theJOX (Java Objects in XML) library, visit

XML Business Delegate

The XML Business Delegate provides the client with a Business Delegate that uses XML as input and output (return) parameters. As previously illustrated in Figure 1, the combination of the DTO, the Session Facade, the Business Delegate and the mapping between DTOs and XML build the infrastructure for achieving the XML Business Delegate solution.

Figure 9 has the class diagram for the XML Business Delegate with its relationship to the SessionFacade, and XML empowered DTOs.

Figure 9 - XML Business Delegate class diagram

A DTO that is to be instantiated from an XML document received as a parameter of a Business Delegate method, must implement the InXML interface. The InXML interface has two objectives: it marks the DTO as a DTO generated from an input XML document parameter, and it enforces the DTO class to provide the fromXML() method. Similarly to the InXML interface, the OutXML interface marks the DTO and ensures the toXML() method implementation. By having InXML and OutXML interfaces, all DTOs matching input and output parameters of the XML Business Delegate are clearly and explicitly marked.

Figure 10 shows a sequence diagram similar to the one in Figure 7. But in this version, the client is using the XML Business Delegate instead of going directly to the Session Facade.

Figure 10 - New versions for the getAccountHistory operation

Listing 7 shows the XML Business Delegate code for the getAccountHistory operation, while Listing 8 shows the respective code for the client.

Listing 7: BankSystemXMLBusinessDelegate class

import java.rmi.RemoteException;
import javax.ejb.*;

public class BankSystemXMLBusinessDelegate {
  // Service locator can be used for getting and caching EJBHomes
  private BankSystemSessionFacadeHome sessionFacadeHome = null;

  public BankSystemXMLBusinessDelegate(){
    // Get bankSystemSessionFacadeHome reference

  public String getAccountHistory(String accountContextXMLString)
     throws BankSystemException {
    try {
        sessionFacade = sessionFacadeHome.create();
      // convert the XML into a DTO object
      AccountHistoryContext accountHistoryContext =
          new AccountHistoryContext().fromXML(accountContextXMLString);
      // generate the XML for the DTO object
      AccountHistory accountHistory =
      return accountHistory.toXML();
    catch (SessionFacadeException sfExc) {
      throw new BankSystemException("Error in get history  operation", sfExc);
    catch (javax.ejb.CreateException createExc) {
      throw new BankSystemException("Error in get history  operation", createExc);
    catch (java.rmi.RemoteException remoteExc) {
      throw new BankSystemException("Error in get history  operation", remoteExc);

  public String transfer(String transferRequestXMLString)
     throws BankSystemException {
    try {
        sessionFacade = sessionFacadeHome.create();
      // convert the XML into a DTO object
      TransferOperation transferRequest =
          new TransferOperation().fromXML(transferRequestXMLString);
      TransferOperation transferResult =
      // generate the XML for the DTO object
      return transferResult.toXML();
    catch (SessionFacadeException sfExc) {
      throw new BankSystemException("Error during transfer operation", sfExc);
    catch (javax.ejb.CreateException createExc) {
      throw new BankSystemException("Error during transfer operation", createExc);
    catch (java.rmi.RemoteException remoteExc) {
      throw new BankSystemException("Error during transfer operation", remoteExc);

Listing 8: The client code using XML Business Delegate

// ...
      BankSystemXMLBusinessDelegate xmlBusDelegate =
          new BankSystemXMLBusinessDelegate();

      String accHistoryXML =
      // eg: show the accHistoryXML in a web application
    } catch (BankSystemException exc){
// ...

The following are some important points about the XML Business Delegate:

  • The client is aware only of the input and output XML documents and the XML Business Delegate methods.
  • A DTO class that is used as an argument of a SessionFacade method and is originated from an XML document implements the InXML interface.
  • A DTO class that is used as a return of a SessionFacade method and is converted into an XML document implements the OutXML interface.
  • EJB classes don't implement XML manipulation; instead, the DTO itself encapsulates the manipulation of its representation into such a format.

Web Services

The concept of Web services is the beginning of a new service-oriented architecture. Web services defines a new view on the paradigm of distributed programming and provision of applications, which is firmly attached to the public Internet. Web services enable the development of self-describing applications that can discover and engage other Web applications to complete complex tasks over the Internet.

Figure 11 shows a Web services architecture which is defined in terms of three roles - service provider, service requestor and service registry - and the interactions between them: publish, find, bind.

Figure 11 - Web services Architecture

Basically, a service implemented by a Service Provider is described and published in the Service Registry. A Service Requester finds the service description via the Service Registry, and then binds to the Service Provider to use the service. Technologies such as SOAP, WSDL and UDDI help provide the basis for communication and discovery of web service implementations. These standards provide the infrastructure to publish (WSDL, UDDI), find (WSDL, UDDI) and bind (WSDL, SOAP) Web services.

XML Business Delegate and Web Services

The Web services Description Language (WSDL) provides a standard way of capturing service descriptions. WSDL describes a service as a set of 'ports' which group related interactions that are possible between the Service Requestor and the Service Provider. Such interactions are described as 'operations', which may have an input message, and optionally a resulting output message.

Figure 12 - XML Business Delegate and Web services

As depicted in Figure 12, the XML Business Delegate offers a possible infrastructure for service implementation in the following way:

  • XML Business Delegate methods are mapped to Web services operations,
  • XML Business Delegate methods' input and output parameters, which are already represented as XML, build the input and output messages of a Web services operation.


The XML Business Delegate provides a solution to facilitate a mapping from an object-oriented system to a service-oriented one. Several solutions and standards are coming with Web services; the one presented in this article shows how the combination of the DTO, the Session Facade, the Business Delegate and XML can bring an EJB development in the direction of XML-based technologies such as Web services.


  1. Floyd Marinescu, EJB Design Patterns: Advanced Patterns, Processes, and Idioms, John Wiley & Sons, 2000. On the Web /books/EJBDesignPatterns/index.tss
  2. E. Gamma, R. Helm, R. E. Johnson, and J. Vlissides, Design Patterns, Elements of Reusable Object-Oriented Software, Addison-Wesley, 1995.
  3. Sun Java Center J2EE Patterns, Java Developer Connection [Sun 2001]

About the Author

Paulo Caroli,, MSc Software Engineer, is a Senior Java Developer with more than 8 years of experience in Application Development. He is an expert in Object Oriented techniques who specialized in J2EE Web application development. He currently works for OmniPros ( as an IT Designer consultant at Cisco Systems.