Wednesday, September 9, 2015

Contacting server with GWT. And complete example of RPC call.

There are couple of  possibilities to hit the database with GWT like RequestFactory and RPC.

Before getting started with server calls please go through,

 - GWT RPC (Which makes server calls Asynchronously)

 - RequestFactory (Alternative to GWT-RPC  which use proxies in between).

In this perticular post, let see the complete example of GWT RPC call to server.

Simple RPC structure can show  as below :

 GWT Code <===> InterfaceAsync <===> Interface (Synchronous)<===> Server Code 

Ok, Let's write code for small RPC, which is a PingPong. Client just says Ping to server and server responds with Pong.

ASynchronous Interface PingPongRPCInterfaceAsync , which we can able to access on client side.

     public interface PingPongRPCInterfaceAsync {  
     public void PingPongRPC (String message, AsyncCallback callback);  

The Synchronous Interface PingPongRPCInterface

   public interface PingPongRPCInterface extends RemoteService {  
     public String PingPongRPC(String message);  

Here is the  Service layer class which is equals to Servlet in J2EE and which implements our server side interface PingPongRPCInterface.

    public class PingPongRPCImpl extends  RemoteServiceServlet implements PingPongRPCInterface {  
     private static final long serialVersionUID = 1L;  
     public String pingPongRPC(Sting message)  
       // Hey I received a message here from client   
             // And sending response to client back   
       System.out.println("Message from client" + message);       
       String serverResponse= "Pong";  
       return serverResponse;              

Map the above server impl class in your web.xml;


We all done with implementation part and let see how we can use this service call in our client side.

       private final pingPongRPCInterfaceAsync beanService =  
       ServiceDefTarget endpoint = (ServiceDefTarget) service;  

Once you register your service you can just invoke the method from your client interface as

String message = "Ping to server";  
   beanService.pingPongRPC(message, callback);  
    AsyncCallback callback = new AsyncCallback()  
       public void onFailure(Throwable caught)  
         //Do on fail  
       public void onSuccess(String result)  
         //Process successfully done with result  

And please note down the below package structures:

PingPongRPCInterfaceAsync ,pingPongRPCInterface should be in client* package
PingPongRPCImpl   should be in  server package.

That's a complete example of RPC. Please post in comments if you have any doubt or exception in middle of RPC.


No comments:

Post a Comment