`

GWT RPC原理浅析

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

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

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


创建一个RPC,我们需要创建一个Servlet继承RemoteServiceServlet
当页面调用一个RPC时便进入了这个Servlet的doPost方法,此方法在
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实现了这个方法:

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 等辅助类,核心功能是编码解码请求

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics