清单7:DemoClient代码清单
1 package com.sample.myProject.client;
2 import com.google.gwt.core.client.EntryPoint; 3 import com.google.gwt.core.client.GWT; 4 import com.google.gwt.user.client.rpc.AsyncCallback; 5 import com.google.gwt.user.client.rpc.ServiceDefTarget; 6 import com.google.gwt.user.client.ui.Button; 7 import com.google.gwt.user.client.ui.ClickListener; 8 import com.google.gwt.user.client.ui.Label; 9 import com.google.gwt.user.client.ui.RootPanel; 10 import com.google.gwt.user.client.ui.Widget;
/** * This class is used to demostrate hwo to * interact with the server client in asynchronized * way */ 11 public class DemoClient implements EntryPoint {
12 public void onModuleLoad() { 13final SampleServiceAsync sampleService = (SampleServiceAsync) 14 GWT.create(SampleService.class); 15 ServiceDefTarget target = (ServiceDefTarget)sampleService; 16 String staticResponseURL = GWT.getModuleBaseURL(); 17 staticResponseURL += "/getStringService"; 18 target.setServiceEntryPoint(staticResponseURL); 19 20 final Label label = new Label(); 21 final Button button = new Button("Get String"); 22 button.addClickListener(new ClickListener() { 23 public void onClick(Widget sender) { 24 sampleService.getString(new AsyncCallback() { 25 public void onSuccess(Object result) { 26 label.setText((String) result); 27 } 28 public void onFailure(Throwable caught) { 29 label.setText(caught.getMessage()); 30 } 31 }); 32 } 33 });
34 RootPanel.get("1").add(button); 35 RootPanel.get("2").add(label); 36 } 37} |
代码的第13行得到了一个实现了接口SampleServiceAsync的类的实例。第15行创建了一个ServiceDefTarget对象的一个实例,通过这个对象可以设置请求的目的地。程序的第18行设置了请求的目的地的URL,在我们的例子中是"/getStringService",这个URL会在web.xml文件中被mapping到servlet SampleServiceImpl上。程序的22行到33行为我们添加的button设置了单击响应事件。在单击响应事件中调用sampleService的getString(AsyncCallback callback);方法。这个方法是用来进行异步的远程过程调用的(RPC).并且在实现接口AsyncCallback的代码中指定了回调函数,当远程过程调用成功后就执行onSuccess(Object result)函数,其中result中存放有从服务器端返回的结果.。在远程工程调用失败后就执行onFailure(Throwable caught)函数。程序的最后把Button组件和Label组件加到panel中。
现在我们已经完成了程序的开发,图八显示了我们程序的运行结果,在点击Button后,右边回打出一句话来,重要的是这句话是以异步的方式从服务器端取得的,不需要进行页面的刷新,怎么样,现在是不是也想用GWT进行Ajax应用开发了呢?

图八:RPC调用示例
总结
本文主要对用 GWT 进行 Ajax 开发进行了比较详细的介绍,并通过与传统的Ajax开发方式进行比较,使读者能更清楚地理解它们之间的区别,最后我们可以看出用GWT进行Ajax开发可以使得程序员免受调试Javascript之苦,并且GWT自动处理了浏览器之间的兼容性问题,这些都会使得开发更加容易,快捷。因此,用GWT进行Ajax开发是一种比较好的方式。希望本文能为读者学习GWT进行Ajax的开发有所帮助。
(责任编辑:铭铭 mingming_ky@126.com TEL:(010)68476636)