gwt

GWT AsyncCallback Example

In previous GWT tutorials we have seen how to setup basic project, how to create GUI using GWT Widgets and few more GUI related chapters. As part of this tutorial we are going to look into how GWT Web Application interacts with a backend server.

GWT provides a couple of different ways to communicate with a server via HTTP. We can use the GWT Remote Procedure Call (RPC) framework to transparently make calls to Java servlets. GWT AsynchCAllback is the primary interface that a caller must implement to receive a response from a RPC.

Here we are using GWT 2.7 integrated with Eclipse Mars 4.5.
 

1. Introduction

Typically Client communicates with server uses RPC (Remote Procedure Call). RPC is essentially a way of invoking a method in a class, however the only difference is that the class is located on a server, not actually the part of client program you are running. There is a problem with RPC, as Javascripts runs in web browser and the RPC call from browser hangs browser until the response is received. To avoid the browser hanging, GWT RPC call is made “Asynchronous” and the browser does not hang while waiting for the response.

2. GWT RPC Mechanism

The implementation of GWT RPC is based on the Java Servlet technology. GWT allows Java Objects to communicate between the client and the server; which are automatically serialized by the framework. The server-side code that gets invoked from the client is usually referred to as a service and the remote procedure call is referred as invoking a service.
Below diagram shows the RPC implementation in a GWT application.

GWT RPC Mechanism
GWT RPC Mechanism

2. Creating Service

An interface at client-side that defines all service methods and the only way to communicate between client and server. The service is available at client-side, therefore it must be placed in the client package.

2.1 Define service Interface

To develop a new service interface, we will be creating a client-side Java interface that extends the RemoteService interface.

SampleService.java

import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;

@RemoteServiceRelativePath("sampleservice")
public interface SampleService extends RemoteService{

	String sayHello(String name);
}

2.2 Define Async Service Interface

The service will be erroneous until we define the same service inside Async interface with return type void and the callback object for the Async service. The name of this interface must be the service interface name concatenated with “Async”.

SampleServiceAsync.java

import com.google.gwt.user.client.rpc.AsyncCallback;

public interface SampleServiceAsync {

	void sayHello(String name, AsyncCallback callback);

}

2.4 Implementing AsynchCallback and handling its Failure

The interface AsyncCallback defines two methods OnSuccess and OnFailure. A class needs to be implemented to receive a callback from server and provide functionality on failure/success in the communication.

SampleCallback.java

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;

/**
 * Class which handles the asynchronous callback from the server
 * 
 * Need to react on server communication failure and success
 */
public class SampleCallback implements AsyncCallback {

	@Override
	public void onFailure(Throwable caught) {
		// handle failure from server.
		Window.alert("Not able to process client reuest. Exception occured at server: " + caught);
	}

	@Override
	public void onSuccess(String result) {
		// handle the successful scenario. 
		Window.alert("Client request processed sucessfully. Result from server: " + result);
	}
}

3. Implementing Service

Services are responsible to perform some processing to respond to client requests. Such server-side processing occurs in the service implementation, which is based on the well-known servlet architecture.

3.1 Define Service Interface Implementation

GWT service implementation must extend RemoteServiceServlet and must implement the associated service interface.
Every service implementation is ultimately a servlet. However it extends RemoteServiceServlet instead of HttpServlet. RemoteServiceServlet automatically handles serialization of the data being passed between the client and the server and invoking the intended method in your service implementation.

SampleServiceImpl.java

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.javacodegeeks.helloworld.client.service.SampleService;

public class SampleServiceImpl extends RemoteServiceServlet implements SampleService {

	@Override
	public String sayHello(String name) {
		return "Hello " + name;
	}

}

3.2 Update entry of Service inside web.xml

Define the servlet and map the URL to particular service by using the short-cute name of the service or fully qualified name of the service.

web.xml

<!-- Servlets -->
<servlet>
    <servlet-name>sampleServlet</servlet-name>
    <servlet-class<com.javacodegeeks.helloworld.server.SampleServiceImpl</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>sampleServlet>/servlet-name>
    <url-pattern>/samplewebapplication/sampleservice</url-pattern>
</servlet-mapping>
</pre>

4. Example

This shows that the user enters value inside and test box and clicks on button and a client request goes to server and response is getting handled on GUI. On successful completion, the label gets updated otherwise an alert windows apeears.

SampleWebApplication.java

/**
 * Entry point classes define onModuleLoad().
 */
public class SampleWebApplication implements EntryPoint, ClickHandler{

	/**
	 * Instantiates service.
	 */
	SampleServiceAsync sampleServiceAsync = GWT.create(SampleService.class);
	/**
	 * Label & Text Box.
	 */
	Label lbl; TextBox textBox;
	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {

		VerticalPanel verticalPanel = new VerticalPanel();
		verticalPanel.setSize("100%", "100%"); 
		verticalPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
		verticalPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		textBox = new TextBox();
		Button btn = new Button("Get Update from Server"); btn.addClickHandler(this);
		lbl = new Label("The text will be updated here.");
		Image image = new Image();
		image.setUrl("https://www.javacodegeeks.com/wp-content/uploads/2012/12/JavaCodeGeeks-logo.png");

		verticalPanel.add(textBox); verticalPanel.add(btn); verticalPanel.add(lbl);
		verticalPanel.add(image);
		
		RootLayoutPanel.get().add(verticalPanel);
	}
	
	@Override
	public void onClick(ClickEvent event) {
		sampleServiceAsync.sayHello(textBox.getText(), new AsyncCallback() {

			@Override
			public void onFailure(Throwable caught) {
				// handle failure from server.
				Window.alert("Exception Received from server.");
			}

			@Override
			public void onSuccess(String result) {
				lbl.setText(result);
			}
		});
	}
}

Output:

5. References

• Using GWT RPC
• GWT API Reference

6. Download Eclipse Project

Download
You can download the full source code of this example here: GWT AsyncCallback Example

Abhishek Gupta

Abhishek Kumar Gupta with an engineering degree in Computer Science and Engineering from Harcourt Butler Technological Institute India. During the tenure of 7.5 years, Abhishek has been involved with a large number of projects ranging from programming, architecture designing and requirement analysis. He is currently working as Technical Lead with one of the biggest product based company - Ciena The Network Specialist with extensive work experience with JAVA/J2EE technologies with Telecom domain.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button