基於GWT的應用程式通常由客戶端模塊和伺服器端模塊組成。客戶端代碼在瀏覽器中運行,伺服器端代碼在web伺服器中運行。客戶端代碼必須通過網絡發出HTTP請求才能訪問伺服器端數據。
遠程過程調用(RPC,Remote Procedure Call)是GWT使用的一種機制,其中客戶端代碼可以直接執行伺服器端方法。
GWT-RPC是基於servlet的。
GWT-RPC是異步的,客戶機在通信期間從不被阻塞。
使用GWT RPC Java對象可以直接在客戶機和伺服器之間發送(由GWT框架自動序列化)。
伺服器端servlet被稱爲服務。
從客戶端代碼調用伺服器端servlet方法的遠程過程調用稱爲調用服務。
GWT RPC Components
以下是GWT-RPC通信機制中使用的三個組件
- A remote service (server-side servlet) that runs on the server.
- Client code to invoke that service.
- Java data objects which will be passed between client and server.
GWT客戶機和伺服器都會自動序列化和反序列化數據,因此不需要開發人員序列化/反序列化對象,數據對象可以通過HTTP進行傳輸。
下圖顯示了RPC體系結構。
要開始使用RPC,我們需要遵循GWT約定。
RPC Communication Workflow
Step 1 - Create a Serializable Model Class
在客戶端定義一個java模型對象,該對象應該是可序列化的。
public class Message implements Serializable { ... private String message; public Message(){}; public void setMessage(String message) { this.message = message; } ... }
Step 2 - Create a Service Interface
在客戶端爲服務定義一個接口,該接口擴展列出所有服務方法的RemoteService。
使用annotation@remoteservicererelativepath將服務映射爲遠程servlet相對於模塊基URL的默認路徑。
@RemoteServiceRelativePath("message") public interface MessageService extends RemoteService { Message getMessage(String input); }
Step 3 - Create a Async Service Interface
在客戶機端(與上面提到的服務位於同一位置)定義一個異步服務接口,該接口將在GWT客戶機代碼中使用。
public interface MessageServiceAsync { void getMessage(String input, AsyncCallback<Message> callback); }
Step 4 - Create a Service Implementation Servlet class
在伺服器端實現接口,該類應擴展RemoteServiceServlet類。
public class MessageServiceImpl extends RemoteServiceServlet implements MessageService{ ... public 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
編輯web應用程式部署描述符(web.xml)以包含MessageServiceImpl Servlet聲明。
<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 Application Code
創建服務代理類。
MessageServiceAsync messageService = GWT.create(MessageService.class);
創建AsyncCallback處理程序以處理伺服器將消息返回給客戶端的RPC回調
class MessageCallBack implements AsyncCallback<Message> { @Override public void onFailure(Throwable caught) { Window.alert("Unable to obtain server response: " + caught.getMessage()); } @Override public void onSuccess(Message result) { Window.alert(result.getMessage()); } }
當用戶與UI交互時調用遠程服務
public class HelloWorld implements EntryPoint { ... public void onModuleLoad() { ... buttonMessage.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { messageService.getMessage(txtName.getValue(), new MessageCallBack()); } }); ... } }
RPC Communication Complete Example
這個例子將帶您通過簡單的步驟來展示GWT中RPC通信的例子。按照以下步驟更新我們在GWT-Create application−一章中創建的GWT應用程式;
Step | Description |
---|---|
1 | Create a project with a name HelloWorld under a package com.tutorialspoint as explained in the GWT - Create Application 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 application to verify the result of the implemented logic. |
下面是修改後的模塊描述符的內容。
<?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.client.HelloWorld'/> <!-- Specify the paths for translatable code --> <source path = 'client'/> <source path = 'shared'/> </module>
下面是修改後的樣式表文件war/HelloWorld.css的內容。
body { text-align: center; font-family: verdana, sans-serif; } h1 { font-size: 2em; font-weight: bold; color: #777777; margin: 40px 0px 70px; text-align: center; }
下面是修改後的HTML宿主文件war/HelloWorld.HTML的內容。
<html> <head> <title>Hello World</title> <link rel = "stylesheet" href = "HelloWorld.css"/> <script language = "javascript" src = "helloworld/helloworld.nocache.js"> </script> </head> <body> <h1>RPC Communication Demonstration</h1> <div id = "gwtContainer"></div> </body> </html>
package com.tutorialspoint.client; import java.io.Serializable; public class Message implements Serializable { private static final long serialVersionUID = 1L; private String message; public Message(){}; public void setMessage(String message) { this.message = message; } public String getMessage() { return message; } }
package com.tutorialspoint.client; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; @RemoteServiceRelativePath("message") public interface MessageService extends RemoteService { Message getMessage(String input); }
package com.tutorialspoint.client; import com.google.gwt.user.client.rpc.AsyncCallback; public interface MessageServiceAsync { void getMessage(String input, AsyncCallback<Message> callback); }
package com.tutorialspoint.server; import com.google.gwt.user.server.rpc.RemoteServiceServlet; import com.tutorialspoint.client.Message; import com.tutorialspoint.client.MessageService; public class MessageServiceImpl extends RemoteServiceServlet implements MessageService{ private static final long serialVersionUID = 1L; public Message getMessage(String input) { String messageString = "Hello " + input + "!"; Message message = new Message(); message.setMessage(messageString); return message; } }
更新修改後的web應用程式部署描述符的內容,使其包含MessageServiceImpl Servlet聲明。
<?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <!-- Default page to serve --> <welcome-file-list> <welcome-file>HelloWorld.html</welcome-file> </welcome-file-list> <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>
package com.tutorialspoint.client; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyUpEvent; import com.google.gwt.event.dom.client.KeyUpHandler; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.DecoratorPanel; import com.google.gwt.user.client.ui.HasHorizontalAlignment; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.VerticalPanel; public class HelloWorld implements EntryPoint { private MessageServiceAsync messageService = GWT.create(MessageService.class); private class MessageCallBack implements AsyncCallback<Message> { @Override public void onFailure(Throwable caught) { /* server side error occured */ Window.alert("Unable to obtain server response: " + caught.getMessage()); } @Override public void onSuccess(Message result) { /* server returned result, show user the message */ Window.alert(result.getMessage()); } } public void onModuleLoad() { /*create UI */ final TextBox txtName = new TextBox(); txtName.setWidth("200"); txtName.addKeyUpHandler(new KeyUpHandler() { @Override public 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("Click Me!"); buttonMessage.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent 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.setCellHorizontalAlignment(buttonMessage, HasHorizontalAlignment.ALIGN_RIGHT); DecoratorPanel panel = new DecoratorPanel(); panel.add(vPanel); // Add widgets to the root panel. RootPanel.get("gwtContainer").add(panel); } }
完成所有更改後,讓我們以開發模式編譯並運行應用程式,就像我們在「gwt-創建應用程式」一章中所做的那樣。如果你的申請一切順利,這將產生以下結果;