8.HttpInvokerServiceExporter导出和执行远程调用服务:
HttpInvokerServiceExporter响应客户端发送的远程调用HTTP请求,它从HTTP请求中读取远程调用并将其反序列化为RemoteInvocation对象,然后调用目标服务对象的目标方法完成远程调用服务,当服务执行完成之后,通过HTTP响应把执行结果对象序列化输出到客户端。器源码如下:
[java] view plaincopyprint
- public class HttpInvokerServiceExporter extends RemoteInvocationSerializingExporter implements HttpRequestHandler { //处理客户端发来的远程调用HTTP请求
- public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- try { //从HTTP请求中反序列化出RemoteInvocation远程调用对象
- RemoteInvocation invocation = readRemoteInvocation(request); //调用目标服务对象,完成远程调用请求,并创建调用结果
- RemoteInvocationResult result = invokeAndCreateResult(invocation, getProxy()); //将调用结果写到HTTP响应中
- writeRemoteInvocationResult(request, response, result); }
- catch (ClassNotFoundException ex) { throw new NestedServletException("Class not found during deserialization", ex);
- } }
- //从HTTP请求中读取RemoteInvocation远程调用对象入口方法 protected RemoteInvocation readRemoteInvocation(HttpServletRequest request) throws IOException, ClassNotFoundException {
- //将从HTTP请求中读取远程调用对象 return readRemoteInvocation(request, request.getInputStream());
- } //从HTTP请求中读取远程调用对象
- protected RemoteInvocation readRemoteInvocation(HttpServletRequest request, InputStream is) throws IOException, ClassNotFoundException { //根据HTTP请求输入流创建对象输入流
- ObjectInputStream ois = createObjectInputStream(decorateInputStream(request, is)); try {
- //从对象输入流中读取远程调用对象 return doReadRemoteInvocation(ois);
- } finally {
- ois.close(); }
- } //获取HTTP请求输入流
- protected InputStream decorateInputStream(HttpServletRequest request, InputStream is) throws IOException { return is;
- } //将远程调用执行结果写到HTTP响应中
- protected void writeRemoteInvocationResult( HttpServletRequest request, HttpServletResponse response, RemoteInvocationResult result) throws IOException {
- //设置HTTP响应的内容类型为:application/x-java-serialized-object response.setContentType(getContentType());
- //将远程调用结果写到HTTP响应中 writeRemoteInvocationResult(request, response, result, response.getOutputStream());
- } //将远程调用执行结果写入HTTP响应中
- protected void writeRemoteInvocationResult( HttpServletRequest request, HttpServletResponse response, RemoteInvocationResult result, OutputStream os)
- throws IOException { //获取HTTP响应对象输出流
- ObjectOutputStream oos = createObjectOutputStream(decorateOutputStream(request, response, os)); try {
- //将远程调用执行结果写到HTTP响应对象输出流中 doWriteRemoteInvocationResult(result, oos);
- } finally {
- oos.close(); }
- } //获取HTTP响应对象输入流
- protected OutputStream decorateOutputStream( HttpServletRequest request, HttpServletResponse response, OutputStream os) throws IOException {
- return os; }
- }