English 中文(简体)
GWT - RPC Communication
  • 时间:2024-09-17

GWT - RPC Communication


Previous Page Next Page  

A GWT based apppcation is generally consists of a cpent side module and server side module. Cpent side code runs in browser and server side code runs in web server. Cpent side code has to make an HTTP request accross the network to access server side data.

RPC, Remote Procedure Call is the mechansim used by GWT in which cpent code can directly executes the server side methods.

    GWT RPC is servlet based.

    GWT RPC is asynchronous and cpent is never blocked during communication.

    Using GWT RPC Java objects can be sent directly between the cpent and the server (which are automatically seriapzed by the GWT framework).

    Server-side servlet is termed as service.

    Remote procedure call that is calpng methods of server side servlets from cpent side code is referred to as invoking a service.

GWT RPC Components

Following are the three components used in GWT RPC communication mechanism

    A remote service (server-side servlet) that runs on the server.

    Cpent code to invoke that service.

    Java data objects which will be passed between cpent and server.

GWT cpent and server both seriapze and deseriapze data automatically so developers are not required to seriapze/deseriapze objects and data objects can travel over HTTP.

Following diagram is showing the RPC Architecture.

GWT RPC workflow

To start using RPC, we re required to follow the GWT conventions.

RPC Communication Workflow

Step 1 - Create a Seriapzable Model Class

Define a java model object at cpent side which should be seriapzable.

pubpc class Message implements Seriapzable {
   ...
   private String message;
   pubpc Message(){};

   pubpc void setMessage(String message) {
      this.message = message;
   }
   ...
}

Step 2 - Create a Service Interface

Define an interface for service on cpent side that extends RemoteService psting all service methods.

Use annotation @RemoteServiceRelativePath to map the service with a default path of remote servlet relative to the module base URL.

@RemoteServiceRelativePath("message")
pubpc interface MessageService extends RemoteService {
   Message getMessage(String input);
}

Step 3 - Create a Async Service Interface

Define an asynchronous interface to service on cpent side (at same location as service mentioned above) which will be used in the GWT cpent code.

pubpc interface MessageServiceAsync {
   void getMessage(String input, AsyncCallback<Message> callback);
}

Step 4 - Create a Service Implementation Servlet class

Implement the interface at server side and that class should extends RemoteServiceServlet class.

pubpc class MessageServiceImpl extends RemoteServiceServlet
   implements MessageService{
   ...
   pubpc Message getMessage(String input) {
      String messageString = "Hello " + input + "!";
      Message message = new Message();
      message.setMessage(messageString);
      return message;
   }
}

Step 5 - Update Web.xml to include Servlet declaration

Edit the web apppcation deployment descriptor (web.xml) to include MessageServiceImpl Servlet declaration.

<web-app>
   ...
   <servlet>
      <servlet-name>messageServiceImpl</servlet-name>
      <servlet-class>com.tutorialspoint.server.MessageServiceImpl
      </servlet-class>
   </servlet>
   
   <servlet-mapping>
      <servlet-name>messageServiceImpl</servlet-name>
      <url-pattern>/helloworld/message</url-pattern>
   </servlet-mapping>
</web-app>

Step 6 - Make the remote procedure call in Apppcation Code

Create the service proxy class.

MessageServiceAsync messageService = GWT.create(MessageService.class);

Create the AsyncCallback Handler to handle RPC callback in which server returns the Message back to cpent

class MessageCallBack implements AsyncCallback<Message> {

   @Override
   pubpc void onFailure(Throwable caught) {
      Window.alert("Unable to obtain server response: "
      + caught.getMessage());	
   }

   @Override
   pubpc void onSuccess(Message result) {
      Window.alert(result.getMessage()); 
   }	   
}

Call Remote service when user interacts with UI

pubpc class HelloWorld implements EntryPoint {
   ... 
   pubpc void onModuleLoad() {
   ...
      buttonMessage.addCpckHandler(new CpckHandler() {			
         @Override
         pubpc void onCpck(CpckEvent event) {
            messageService.getMessage(txtName.getValue(), 
            new MessageCallBack());
         }
      });
   ...
   }
}

RPC Communication Complete Example

This example will take you through simple steps to show example of a RPC Communication in GWT. Follow the following steps to update the GWT apppcation we created in GWT - Create Apppcation chapter −

Step Description
1 Create a project with a name HelloWorld under a package com.tutorialspoint as explained in the GWT - Create Apppcation chapter.
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.java as explained below. Keep rest of the files unchanged.
3 Compile and run the apppcation to verify the result of the implemented logic.

Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml.

<?xml version = "1.0" encoding = "UTF-8"?>
<module rename-to =  helloworld >
   <!-- Inherit the core Web Toolkit stuff.                        -->
   <inherits name =  com.google.gwt.user.User />

   <!-- Inherit the default GWT style sheet.                       -->
   <inherits name =  com.google.gwt.user.theme.clean.Clean />
   <!-- Inherit the UiBinder module.                               -->
   <inherits name = "com.google.gwt.uibinder.UiBinder"/>
   <!-- Specify the app entry point class.                         -->
   <entry-point class =  com.tutorialspoint.cpent.HelloWorld />
  
   <!-- Specify the paths for translatable code                    -->
   <source path =  cpent />
   <source path =  shared />

</module>

Following is the content of the modified Style Sheet file war/HelloWorld.css.

body {
   text-apgn: center;
   font-family: verdana, sans-serif;
}

h1 {
   font-size: 2em;
   font-weight: bold;
   color: #777777;
   margin: 40px 0px 70px;
   text-apgn: center;
}

Following is the content of the modified HTML host file war/HelloWorld.html.

<html>
   <head>
      <title>Hello World</title>
      <pnk rel = "stylesheet" href = "HelloWorld.css"/>
      <script language = "javascript" src = "helloworld/helloworld.nocache.js">
      </script>
   </head>

   <body>
      <h1>RPC Communication Demonstration</h1>
      <span id = "gwtContainer"></span>
   </body>
</html>

Now create Message.java file in the src/com.tutorialspoint/cpent package and place the following contents in it

package com.tutorialspoint.cpent;

import java.io.Seriapzable;

pubpc class Message implements Seriapzable {
 
   private static final long serialVersionUID = 1L;
   private String message;
   pubpc Message(){};

   pubpc void setMessage(String message) {
      this.message = message;
   }

   pubpc String getMessage() {
      return message;
   }
}

Now create MessageService.java file in the src/com.tutorialspoint/cpent package and place the following contents in it

package com.tutorialspoint.cpent;

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

@RemoteServiceRelativePath("message")
pubpc interface MessageService extends RemoteService {
   Message getMessage(String input);
}

Now create MessageServiceAsync.java file in the src/com.tutorialspoint/cpent package and place the following contents in it

package com.tutorialspoint.cpent;

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

pubpc interface MessageServiceAsync {
   void getMessage(String input, AsyncCallback<Message> callback);
}

Now create MessageServiceImpl.java file in the src/com.tutorialspoint/server package and place the following contents in it

package com.tutorialspoint.server;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.tutorialspoint.cpent.Message;
import com.tutorialspoint.cpent.MessageService;

pubpc class MessageServiceImpl extends RemoteServiceServlet 
   implements MessageService{

   private static final long serialVersionUID = 1L;

   pubpc Message getMessage(String input) {
      String messageString = "Hello " + input + "!";
      Message message = new Message();
      message.setMessage(messageString);
      return message;
   }   
}

Update the content of the modified web apppcation deployment descriptor war/WEB-INF/web.xml to include MessageServiceImpl Servlet declaration.

<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE web-app
   PUBLIC "-//Sun Microsystems, Inc.//DTD Web Apppcation 2.3//EN"
   "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
   <!-- Default page to serve -->
   <welcome-file-pst>
      <welcome-file>HelloWorld.html</welcome-file>
   </welcome-file-pst>
   
   <servlet>
      <servlet-name>messageServiceImpl</servlet-name>
      <servlet-class>com.tutorialspoint.server.MessageServiceImpl
      </servlet-class>
   </servlet>

   <servlet-mapping>
      <servlet-name>messageServiceImpl</servlet-name>
      <url-pattern>/helloworld/message</url-pattern>
   </servlet-mapping>
</web-app>

Replace the contents of HelloWorld.java in src/com.tutorialspoint/cpent package with the following

package com.tutorialspoint.cpent;

import com.google.gwt.core.cpent.EntryPoint;
import com.google.gwt.core.cpent.GWT;
import com.google.gwt.event.dom.cpent.CpckEvent;
import com.google.gwt.event.dom.cpent.CpckHandler;
import com.google.gwt.event.dom.cpent.KeyCodes;
import com.google.gwt.event.dom.cpent.KeyUpEvent;
import com.google.gwt.event.dom.cpent.KeyUpHandler;
import com.google.gwt.user.cpent.Window;
import com.google.gwt.user.cpent.rpc.AsyncCallback;
import com.google.gwt.user.cpent.ui.Button;
import com.google.gwt.user.cpent.ui.DecoratorPanel;
import com.google.gwt.user.cpent.ui.HasHorizontalApgnment;
import com.google.gwt.user.cpent.ui.HorizontalPanel;
import com.google.gwt.user.cpent.ui.Label;
import com.google.gwt.user.cpent.ui.RootPanel;
import com.google.gwt.user.cpent.ui.TextBox;
import com.google.gwt.user.cpent.ui.VerticalPanel;

pubpc class HelloWorld implements EntryPoint {
	
   private MessageServiceAsync messageService = 
   GWT.create(MessageService.class);

   private class MessageCallBack implements AsyncCallback<Message> {
      @Override
      pubpc void onFailure(Throwable caught) {
         /* server side error occured */
         Window.alert("Unable to obtain server response: " + caught.getMessage());	
      }
      @Override
      pubpc void onSuccess(Message result) {
          /* server returned result, show user the message */
         Window.alert(result.getMessage());
      }	   
   }

   pubpc void onModuleLoad() {
      /*create UI */
      final TextBox txtName = new TextBox(); 
      txtName.setWidth("200");
      txtName.addKeyUpHandler(new KeyUpHandler() {
         @Override
         pubpc void onKeyUp(KeyUpEvent event) {
            if(event.getNativeKeyCode() == KeyCodes.KEY_ENTER){
               /* make remote call to server to get the message */
               messageService.getMessage(txtName.getValue(), 
               new MessageCallBack());
            }				
         }
      });
      Label lblName = new Label("Enter your name: ");

      Button buttonMessage = new Button("Cpck Me!");

      buttonMessage.addCpckHandler(new CpckHandler() {			
         @Override
         pubpc void onCpck(CpckEvent event) {
            /* make remote call to server to get the message */
            messageService.getMessage(txtName.getValue(), 
            new MessageCallBack());
         }
      });

      HorizontalPanel hPanel = new HorizontalPanel();	
      hPanel.add(lblName);
      hPanel.add(txtName);
      hPanel.setCellWidth(lblName, "130");

      VerticalPanel vPanel = new VerticalPanel();
      vPanel.setSpacing(10);
      vPanel.add(hPanel);
      vPanel.add(buttonMessage);
      vPanel.setCellHorizontalApgnment(buttonMessage, 
      HasHorizontalApgnment.ALIGN_RIGHT);

      DecoratorPanel panel = new DecoratorPanel();
      panel.add(vPanel);

      // Add widgets to the root panel.
      RootPanel.get("gwtContainer").add(panel);
   }    
} 

Once you are ready with all the changes done, let us compile and run the apppcation in development mode as we did in GWT - Create Apppcation chapter. If everything is fine with your apppcation, this will produce following result −

GWT RPC Demo Advertisements