首页 | 新闻 | 新品 | 文库 | 方案 | 视频 | 下载 | 商城 | 开发板 | 数据中心 | 座谈新版 | 培训 | 工具 | 博客 | 论坛 | 百科 | GEC | 活动 | 主题月 | 电子展
返回列表 回复 发帖

使用 GWT 和 RESTful Web 服务构建动态的组织树(4)

使用 GWT 和 RESTful Web 服务构建动态的组织树(4)

实现 RPC 代理以请求 RESTful Web 服务有几种集成 GWT 和 RESTful Web 服务的策略。如果 RESTful Web 服务在相同的域和端口上运行,明显的方法是使用 GWT RequestBuilder 类。但是,RequestBuilder 类无法克服 Same Original Policy (SOP) 限制,即禁止对不同域中的 Web 服务服务器发出请求。为了避免 SOP 限制,我使用 RPC 代理策略。按照这种策略,GWT 客户机把 RESTful Web 服务发送给 RPC 远程服务,RPC 远程服务把请求传递给 RESTful Web 服务服务器。
创建定制的异常类需要一个特殊的定制异常,让服务器可以把异常传递给客户机。GWT 提供一种非常简便的实现方法。只需让定制的异常类扩展 Exception 类并实现 IsSerializable 接口。定制的异常见清单 7。
清单 7. edu.ucar.cisl.gwtRESTTutorialView.client.RESTfulWebServiceException
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
1.  package edu.ucar.cisl.gwtRESTTutorialView.client;

2.  import com.google.gwt.user.client.rpc.IsSerializable;

3.  public class RESTfulWebServiceException extends Exception implements IsSerializable {
4.      private static final long serialVersionUID = 1L;
5.      private String message;
   
6.      public RESTfulWebServiceException() {
7.      }
   
8.      public RESTfulWebServiceException(String message) {
9.          super(message);
10.         this.message = message;
11.     }
  
12.     public RESTfulWebServiceException(Throwable cause) {
13.         super(cause);
14.     }
  
15.     public RESTfulWebServiceException(String message, Throwable cause) {
16.         super(message, cause);
17.         this.message = message;
18.     }
  
19.     public String getMessage() {
20.         return message;
21.     }
22. }




创建远程服务接口对于每个远程服务,GWT 在客户端需要两个接口:一个远程服务接口和一个远程服务异步接口。远程服务接口必须扩展 GWT RemoteService 接口并定义将向客户机公开的服务方法的签名。方法参数和返回类型必须是可序列化的。
本文使用的远程服务接口非常简单(清单 8)。它只声明一个方法,invokeGetRESTfulWebService。这个方法有两个参数,uri 和 contentType。前者是标识 RESTful Web 服务服务器上要请求的资源的 URI。后者表示应该返回的结果的内容类型。内容类型是标准 HTTP 内容类型之一,比如 application/json、application/xml、application/text 等。这个方法返回 HTTP 响应中的内容字符串,在失败时抛出定制的异常。
需要添加一个 RemoteServiceRelativePath 注解以指定服务的 URL 路径(清单 8 中的第 5 行)。通过创建简单的实用程序类很容易获得异步远程接口的实例(清单 8 中的第 7-13 行)。
清单 8. edu.ucar.cisl.gwtRESTTutorialView.client.RESTfulWebServiceProxy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
1.  package edu.ucar.cisl.gwtRESTTutorialView.client;
2.  import com.google.gwt.core.client.GWT;
3.  import com.google.gwt.user.client.rpc.RemoteService;
4.  import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
   
   
5.  @RemoteServiceRelativePath("RESTfulWebServiceProxy")
6.  public interface RESTfulWebServiceProxy extends RemoteService {
7.      public static class Util {
8.          public static RESTfulWebServiceProxyAsync getInstance() {
9.              RESTfulWebServiceProxyAsync
10. rs=(RESTfulWebServiceProxyAsync)GWT.create(RESTfulWebServiceProxy.class);
11.             return rs;
12.         }
13.      }
14.
15.     public String invokeGetRESTfulWebService(String uri, String contentType)
16.         throws RESTfulWebServiceException;
17. }

返回列表