Spring框架学习[Spring HTTP调用器实现远程调用](八)

2014-11-24 03:00:37 · 作者: · 浏览: 9
VC的一个Controller,客户端发来的远程调用HTTP请求有Spring MVC的中央控制器DispatcherServlet转发到指定URL的HttpInvokerServiceExporter上。

8.HttpInvokerServiceExporter导出和执行远程调用服务:

HttpInvokerServiceExporter响应客户端发送的远程调用HTTP请求,它从HTTP请求中读取远程调用并将其反序列化为RemoteInvocation对象,然后调用目标服务对象的目标方法完成远程调用服务,当服务执行完成之后,通过HTTP响应把执行结果对象序列化输出到客户端。器源码如下:

[java] view plaincopyprint
  1. public class HttpInvokerServiceExporter extends RemoteInvocationSerializingExporter implements HttpRequestHandler { //处理客户端发来的远程调用HTTP请求
  2. public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  3. try { //从HTTP请求中反序列化出RemoteInvocation远程调用对象
  4. RemoteInvocation invocation = readRemoteInvocation(request); //调用目标服务对象,完成远程调用请求,并创建调用结果
  5. RemoteInvocationResult result = invokeAndCreateResult(invocation, getProxy()); //将调用结果写到HTTP响应中
  6. writeRemoteInvocationResult(request, response, result); }
  7. catch (ClassNotFoundException ex) { throw new NestedServletException("Class not found during deserialization", ex);
  8. } }
  9. //从HTTP请求中读取RemoteInvocation远程调用对象入口方法 protected RemoteInvocation readRemoteInvocation(HttpServletRequest request) throws IOException, ClassNotFoundException {
  10. //将从HTTP请求中读取远程调用对象 return readRemoteInvocation(request, request.getInputStream());
  11. } //从HTTP请求中读取远程调用对象
  12. protected RemoteInvocation readRemoteInvocation(HttpServletRequest request, InputStream is) throws IOException, ClassNotFoundException { //根据HTTP请求输入流创建对象输入流
  13. ObjectInputStream ois = createObjectInputStream(decorateInputStream(request, is)); try {
  14. //从对象输入流中读取远程调用对象 return doReadRemoteInvocation(ois);
  15. } finally {
  16. ois.close(); }
  17. } //获取HTTP请求输入流
  18. protected InputStream decorateInputStream(HttpServletRequest request, InputStream is) throws IOException { return is;
  19. } //将远程调用执行结果写到HTTP响应中
  20. protected void writeRemoteInvocationResult( HttpServletRequest request, HttpServletResponse response, RemoteInvocationResult result) throws IOException {
  21. //设置HTTP响应的内容类型为:application/x-java-serialized-object response.setContentType(getContentType());
  22. //将远程调用结果写到HTTP响应中 writeRemoteInvocationResult(request, response, result, response.getOutputStream());
  23. } //将远程调用执行结果写入HTTP响应中
  24. protected void writeRemoteInvocationResult( HttpServletRequest request, HttpServletResponse response, RemoteInvocationResult result, OutputStream os)
  25. throws IOException { //获取HTTP响应对象输出流
  26. ObjectOutputStream oos = createObjectOutputStream(decorateOutputStream(request, response, os)); try {
  27. //将远程调用执行结果写到HTTP响应对象输出流中 doWriteRemoteInvocationResult(result, oos);
  28. } finally {
  29. oos.close(); }
  30. } //获取HTTP响应对象输入流
  31. protected OutputStream decorateOutputStream( HttpServletRequest request, HttpServletResponse response, OutputStream os) throws IOException {
  32. return os; }
  33. }