Communicating with Server using Google Web Toolkit RPC

Exclusive offer: get 50% off this eBook here
Google Web Toolkit 2 Application Development Cookbook

Google Web Toolkit 2 Application Development Cookbook — Save 50%

Google Web Toolkit book and eBook - over 70 simple but incredibly effective practical recipes to develop web applications using GWT with JPA , MySQL and i Report

$23.99    $12.00
by Shamsuddin Ahammad | January 2011 | Cookbooks Open Source

This article deals with the communication between the client and the server. The recipes in this article describe how to use the JPA in the server side and Data Transfer Objects (DTO) in the client side. It discusses how the GWT RPC mechanism allows the server and the client to pass Java objects back and forth.

In this article by Shamsuddin Ahammad, author of Google Web Toolkit 2 Application Development Cookbook, we will cover:

  • Creating DTO classes
  • Mapping entity classes and DTOs
  • Creating a GWT RPC service
  • Defining an RPC method to persist an object
  • Calling an RPC method from a client UI

 

Google Web Toolkit 2 Application Development Cookbook

Google Web Toolkit 2 Application Development Cookbook

Over 70 simple but incredibly effective practical recipes to develop web applications using GWT with JPA , MySQL and i Report

  • Create impressive, complex browser-based web applications with GWT 2
  • Learn the most effective ways to create reports with parameters, variables, and subreports using iReport
  • Create Swing-like web-based GUIs using the Ext GWT class library
  • Develop applications using browser quirks, Javascript,HTML scriplets from scratch
  • Part of Packt's Cookbook series: Each recipe is a carefully organized sequence of instructions to complete the task as efficiently as possible

 

        Read more about this book      

(For more resources on GWT, see here.)

The Graphical User Interface (GUI) resides in the client side of the application. This article introduces the communication between the server and the client, where the client (GUI) will send a request to the server, and the server will respond accordingly. In GWT, the interaction between the server and the client is made through the RPC mechanism. RPC stands for Remote Procedure Call. The concept is that there are some methods in the server side, which are called by the client at a remote location. The client calls the methods by passing the necessary arguments, and the server processes them, and then returns back the result to the client. GWT RPC allows the server and the client to pass Java objects back and forth.

RPC has the following steps:

  1. Defining the GWTService interface: Not all the methods of the server are called by the client. The methods which are called remotely by the client are defined in an interface, which is called GWTService.
  2. Defining the GWTServiceAsync interface: Based on the GWTService interface, another interface is defined, which is actually an asynchronous version of the GWTService interface. By calling the asynchronous method, the caller (the client) is not blocked until the method completes the operation.
  3. Implementing the GWTService interface: A class is created where the abstract method of the GWTService interface is overridden.
  4. Calling the methods: The client calls the remote method to get the server response.

Creating DTO classes

In this application, the server and the client will pass Java objects back and forth for the operation. For example, the BranchForm will request the server to persist a Branch object, where the Branch object is created and passed to server by the client, and the server persists the object in the server database. In another example, the client will pass the Branch ID (as an int), the server will find the particular Branch information, and then send the Branch object to the client to be displayed in the branch form. So, both the server and client need to send or receive Java objects. We have already created the JPA entity classes and the JPA controller classes to manage the entity using the Entity Manager. But the JPA class objects are not transferable over the network using the RPC. JPA classes will just be used by the server on the server side. For the client side (to send and receive objects), DTO classes are used. DTO stands for Data Transfer Object. DTO is simply a transfer object which encapsulates the business data and transfers it across the network.

Getting ready

Create a package com.packtpub.client.dto, and create all the DTO classes in this package.

How to do it...

The steps required to complete the task are as follows:

  1. Create a class BranchDTO that implements the Serializable interface:

    public class BranchDTO implements Serializable

  2. Declare the attributes. You can copy the attribute declaration from the entity classes. But in this case, do not include the annotations:

    private Integer branchId;
    private String name;
    private String location

  3. Define the constructors, as shown in the following code:

    public BranchDTO(Integer branchId, String name, String location)
    {
    this.branchId = branchId;
    this.name = name;
    this.location = location;
    }
    public BranchDTO(Integer branchId, String name)
    {
    this.branchId = branchId;
    this.name = name;
    }
    public BranchDTO(Integer branchId)
    {
    this.branchId = branchId;
    }
    public BranchDTO()
    {
    }

    To generate the constructors automatically in NetBeans, right-click on the code, select Insert Code | Constructor, and then click on Generate after selecting the attribute(s).

  4. Define the getter and setter:

    public Integer getBranchId()
    {
    return branchId;
    }
    public void setBranchId(Integer branchId)
    {
    this.branchId = branchId;
    }
    public String getLocation()
    {
    return location;
    }
    public void setLocation(String location)
    {
    this.location = location;
    }
    public String getName()
    {
    return name;
    }
    public void setName(String name)
    {
    this.name = name;
    }

    To generate the setter and getter automatically in NetBeans, right-click on the code, select Insert Code | Getter and Setter…, and then click on Generate after selecting the attribute(s).

Mapping entity classes and DTOs

In RPC, the client will send and receive DTOs, but the server needs pure JPA objects to be used by the Entity Manager. That's why, we need to transform from DTO to JPA entity class and vice versa. In this recipe, we will learn how to map the entity class and DTO.

Getting ready

Create the entity and DTO classes.

How to do it...

  1. Open the Branch entity class and define a constructor with a parameter of type BranchDTO. The constructor gets the properties from the DTO and sets them in its own properties:

    public Branch(BranchDTO branchDTO)
    {
    setBranchId(branchDTO.getBranchId());
    setName(branchDTO.getName());
    setLocation(branchDTO.getLocation());
    }

  2. This constructor will be used to create the Branch entity class object from the BranchDTO object.
  3. In the same way, the BranchDTO object is constructed from the entity class object, but in this case, the constructor is not defined. Instead, it is done where it is required to construct DTO from the entity class.

There's more...

Some third-party libraries are available for automatically mapping entity class and DTO, such as Dozer and Gilead. For details, you may visit http://dozer.sourceforge.net/ and http://noon.gilead.free.fr/gilead/.

Creating the GWT RPC Service

In this recipe, we are going to create the GWTService interface, which will contain an abstract method to add a Branch object to the database.

Getting ready

Create the Branch entity class and the DTO class.

 

Google Web Toolkit 2 Application Development Cookbook Google Web Toolkit book and eBook - over 70 simple but incredibly effective practical recipes to develop web applications using GWT with JPA , MySQL and i Report
Published: November 2010
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

 

        Read more about this book      

(For more resources on GWT, see here.)

How to do it...

The steps are as follows:

  1. Go to File | New File….
  2. Select Google Web Toolkit from Categories and GWT RPC Service from File Types, as shown in the following screenshot:

    (Move the mouse over the image to enlarge.)

  3. Click on Next.
  4. Give GWTService as the Service Name.
  5. Give rpc as the Subpackage (this is optional), as shown in the following screenshot:

    Google Web Toolkit 2

  6. Click on Finish.

How it works...

A total of three classes are created, which are com.packtpub.client.rpc.GWTService, com.packtpub.client.rpc.GWTServiceAsync, and com.packtpub.server.rpc.GWTServiceImple. Note that GWTService is created in the client-side package, and the implementation class is in the server package. Because of the preceding steps, the following code is generated:

// GWTService.java
package com.packtpub.client.rpc;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
// This is the servlet mapping in web.xml file
@RemoteServiceRelativePath("rpc/gwtservice")
public interface GWTService extends RemoteService
{
public String myMethod(String s);
}
// GWTServiceAsync.java
package com.packtpub.client.rpc;
import com.google.gwt.user.client.rpc.AsyncCallback;
public interface GWTServiceAsync
{
public void myMethod(String s, AsyncCallback<String> callback);
}
// GWTServiceImpl.java
package com.packtpub.server.rpc;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.packtpub.client.rpc.GWTService;
public class GWTServiceImpl extends RemoteServiceServlet
implements GWTService
{
public String myMethod(String s)
{
// Do something interesting with 's' here on the server.
return "Server says: " + s;
}
}

The GWTService interface will include a signature of all the methods which will be called remotely. NetBeans automatically creates a dummy method to understand the concept of RPC. Observe that the myMethod method has no body here; it just has the header part.

An asynchronous version of this method is declared in the GWTServiceAsync interface. The significant changes are:

  1. The return type, String, is changed to void
  2. A new parameter of type AsyncCallback is added

This is because the asynchronous method returns the value through the AsyncCallback object passed to the method as argument.

In addition, the GWTServiceImpl includes implementation of the method.

Defining an RPC method to persist objects

In this recipe, we are going to:

  • Declare an abstract method add in the GWTService interface
  • Declare an abstract asynchronous method add in GWTServiceAsync interface
  • Implement the method in the GWTServiceImpl class

This method will take BranchDTO as a parameter, and add the BranchDTO object in the database.

Getting ready

GWTService, GWTServiceAsync interface, and GWTServiceImpl must be created first.

How to do it...

  1. Open GWTService.java and add the following code:

    public boolean add(BranchDTO branchDTO);

  2. Open GWTServiceAsync.java and add the following code:

    public void add(BranchDTO branchDTO,
    AsyncCallback<java.lang.Boolean> asyncCallback);

  3. Open GWTServiceImpl.java and add the following code:

    @Override
    public boolean add(BranchDTO branchDTO)
    {
    Branch branch = new Branch();
    branch.setBranchId(branchDTO.getBranchId());
    branch.setName(branchDTO.getName());
    branch.setLocation(branchDTO.getLocation());
    BranchJpaController branchJpaController = new
    BranchJpaController();
    boolean added=false;
    try
    {
    branchJpaController.create(branch);
    added=true;
    }
    catch (PreexistingEntityException ex)
    {
    Logger.getLogger(GWTServiceImpl.class.getName()).
    log(Level.SEVERE, null, ex);
    }
    catch (Exception ex)
    {
    Logger.getLogger(GWTServiceImpl.class.getName()).
    log(Level.SEVERE, null, ex);
    }
    return added;
    }

How it works...

Here, we have created a method add to persist a Branch object. As a pure JPA entity class is not transferable through RPC, we have taken the BranchDTO object as a parameter. Then, the JPA entity class is constructed from the DTO class.

Constructing the JPA entity class from the DTO needs just the following steps:

  1. Creating an instance of the JPA entity class (over here, Branch).
  2. Get the properties from the DTO class and set them in the JPA entity class.

After constructing the JPA entity class, the instance of the controller class is created as the controller class contains the necessary methods to persist, update, delete, find, and so on operations. A Boolean variable added is used to track the success of the operation. The variable added is initialized to false and set to true when the persist operation is completed successfully. The create method of the controller class persists the object.

Calling the RPC method from Client UI

In this recipe, we will call the RPC method from the file BranchForm. This method will be called when the Save button is clicked.

How to do it...

  1. Open the file BranchForm.java and create the AsyncCallback instance as follows:

    final AsyncCallback<Boolean> callback =
    new AsyncCallback<Boolean>()
    {
    MessageBox messageBox = new MessageBox();
    @Override
    public void onFailure(Throwable caught)
    {
    messageBox.setMessage("An error occured!
    Cannot save Branch information");
    messageBox.show();
    }
    @Override
    public void onSuccess(Boolean result)
    {
    if (result)
    {
    messageBox.setMessage("Branch information saved
    successfully");
    } else
    {
    messageBox.setMessage("An error occured!
    Cannot save Branch information");
    }
    messageBox.show();
    }
    };

  2. Write the event-handling code for the "add" button, as in the following code. Here, the branchDTO is a class-level instance of BranchDTO.

    saveButton.addSelectionListener(new
    SelectionListener<ButtonEvent>() {
    @Override
    public void componentSelected(ButtonEvent ce)
    {
    branchDTO=new BranchDTO();
    branchDTO.setBranchId(Integer.parseInt
    (branchIdField.getValue()));
    branchDTO.setName(nameField.getValue());
    branchDTO.setLocation(locationField.getValue());
    ((GWTServiceAsync) GWT.create(GWTService.class)) .
    add(branchDTO, callback);
    }
    });

  3. Run the application, open the Branch Form, and enter the input, as shown in the following screenshot:

    Google Web Toolkit 2

  4. Click on the Save button. A confirmation message is shown, as in the following screenshot:

How it works...

Let's now see the aspects in some detail:

  • Creating an AsyncCallback instance: The first step to call the RPC method is to create an instance of the AsyncCallback interface because the result from the server is sent to the client through this instance. The AsyncCallback interface contains the following two abstract methods:
    • onSuccess: This method is called automatically when the operation can be run successfully in the server side. This method has a parameter according to the type of the result the server sends. In our case, this type is Boolean, as we will get the result as true or false after the add operation.
    • onFailure: If the RPC method cannot be invoked for any reason, this method is called automatically. Generally, the error messages are shown from this method.
  • Calling the RPC method: This part handles the calling portion of the RPC method. Here, we have constructed the BranchDTO object and have called the add method of the GWTServiceAsync interface. The GWTServiceAsync object is created by the create method of GWT class. Notice that the AsyncCallback object is passed to the add method, and we receive the result in this object.

Summary

In this article we saw the interaction between the server and the client through the RPC mechanism.

In the next article, Working with Entities in Google Web Toolkit 2, we will see how we can manage entities in GWT RPC.


Further resources on this subject:


Google Web Toolkit 2 Application Development Cookbook Google Web Toolkit book and eBook - over 70 simple but incredibly effective practical recipes to develop web applications using GWT with JPA , MySQL and i Report
Published: November 2010
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

About the Author :


Shamsuddin Ahammad

Shamsuddin Ahammad is a Senior Lecturer and the Course Coordinator at Daffodil Institute of IT, Bangladesh. He has been teaching Java, Programming Methods, and Database Systems since 2002. He has experience in supervising hundreds of academic projects. Shamsuddin has a Masters degree in Management Information Systems (MIS) from Daffodil International University, Dhaka. He obtained the BSc(Hons) degree in Computing & Information Systems (CIS) of NCC Education Ltd, UK and London Metropolitan University joint programme from Daffodil Institute of IT. Before that, he completed the IDCS & IADCS of NCC Education Ltd. He is an Additional Reviewer of Conference on Quality Engineering in Software Technology (CONQUEST) organized by International Software Quality Institute (iSQI) in Germany. He is the author of book titled iReport 3.7 published from PACKT Publishing in March 2010.

Books From Packt


Inkscape 0.48 Essentials for Web Designers
Inkscape 0.48 Essentials for Web Designers

TYPO3 Templates
TYPO3 Templates

CMS Made Simple 1.6: Beginner's Guide
CMS Made Simple 1.6: Beginner's Guide

Blender 2.5 Lighting and Rendering
Blender 2.5 Lighting and Rendering

PostgreSQL 9.0 High Performance
PostgreSQL 9.0 High Performance

PrestaShop 1.3 Theming – Beginner’s Guide
PrestaShop 1.3 Theming – Beginner’s Guide

jQuery 1.4 Reference Guide
jQuery 1.4 Reference Guide

Learning jQuery 1.3
Learning jQuery 1.3


No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
g
v
1
d
m
B
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software