GWT RPC 原理浅析一

本文详细介绍了GWT中RPC机制的实现原理,包括前后台对象的序列化、网络传输及反序列化过程,并通过源码分析了核心方法的执行流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

GWT中前后台交互有多种方式,包括JSON,XML,RPC
其中RPC是GWT提供给我们的功能,他能够让我们直接在前后台传递对象,而无效考虑中间的传递过程。这样的好处是大大提高了我们的开发效率。

GWT是如果后台是如果处理对象,使之序列化,网络传输,反序列化的呢。

下图是RPC过程中的几个核心类。


创建一个RPC,我们需要创建一个Servlet继承RemoteServiceServlet
当页面调用一个RPC时便进入了这个Servlet的doPost方法,此方法在
Java代码 
    AbstraceRemoteServiceServlet中
public final void doPost(HttpServletRequest request,  
      HttpServletResponse response) {  
    // Ensure the thread-local data fields have been initialized  
  
    try {  
      // Store the request & response objects in thread-local storage.  
      //  
      synchronized (this) {  
        validateThreadLocalData();  
        perThreadRequest.set(request);  
        perThreadResponse.set(response);  
      }  
  
      processPost(request, response);  
  
    } catch (Throwable e) {  
      // Give a subclass a chance to either handle the exception or rethrow it  
      //  
      doUnexpectedFailure(e);  
    } finally {  
      // null the thread-locals to avoid holding request/response  
      //  
      perThreadRequest.set(null);  
      perThreadResponse.set(null);  
    }  
  }  





此方法中GWT将request和response放入线程变量,方便之后的调用
核心步骤在processPost(request,response)方法中。
这个方法在AbstractRemoteServiceServlet中是个抽象方法。RemoteServiceServlet实现了这个方法:

Java代码  
    public final void processPost(HttpServletRequest request,  
          HttpServletResponse response) throws IOException, ServletException,  
          SerializationException {  
        // Read the request fully.  
        //  
        String requestPayload = readContent(request);  
      
        // Let subclasses see the serialized request.  
        //  
        onBeforeRequestDeserialized(requestPayload);  
      
        // Invoke the core dispatching logic, which returns the serialized  
        // result.  
        //  
        String responsePayload = processCall(requestPayload);  
      
        // Let subclasses see the serialized response.  
        //  
        onAfterResponseSerialized(responsePayload);  
      
        // Write the response.  
        //  
        writeResponse(request, response, responsePayload);  
      }  



这个核心方法主要的工作是:解析Request中的内容,根据解析出来的内容判断需要调用哪个方法,签名参数是什么。利用反射调用目标Service的方法,最后将返回结果序列化,写入Response。
具体代码上的体现是
1. readContent(request) 解析Request请求
2. processCall(requestPayload) 根据解析出来的结果利用反射调用Servie方法
3. writeResponse(request, response, responsePayload) 将最终结果写入Response

在这些过程中用到了RPC RPCServletUtils 等辅助类,核心功能是编码解码请求



                                                                源自:http://jc-dreaming.iteye.com/blog/1096654


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值