且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

远程servlet之间的通信

更新时间:2023-12-03 14:11:40

取决于。

如果这些Web应用程序在同一个servlet容器中的物理上相同的Web服务器上运行,那么只需将其设置为请求属性并将请求转发到其他上下文:

If those webapplications runs at physically the same webserver in the same servletcontainer, then just set it as a request attribute and forward the request to the other context:

request.setAttribute("name", object);
ServletContext app2 = getServletContext().getContext("app2");
app2.getRequestDispacher("servletUrl").forward(request, response);

其他上下文将能够获得如下对象:

The other context will be able to obtain the object as follows:

Object object = request.getAttribute("name");

这只需要服务器设置,即相互可以访问上下文。如何做到这一点取决于servletcontainer。例如,在 Tomcat 中,您只需要设置 crossContext webapp的< Context> 元素属性为 true

This only requires a server setting that the contexts are accessible by each other. How to do this depends on the servletcontainer. In Tomcat for example, you just need to set crossContext attribute of the webapp's <Context> element to true.

<Context crossContext="true">

然后它将可用于其他上下文。对于其他服务器,请参阅其文档。

Then it will be available to other contexts. For other servers, consult its documentation.

如果这些Web应用程序在物理上不同的Web服务器上运行,则有以下几种选择: / p>

If those webapplications runs at physically different webserver, then there are several options:


  1. 转换为String并作为参数发送。在检索时,从String转换回来。 JSON是一个很好的格式。 Google Gson 提供了在完全可用的Java对象和JSON之间进行转换的可能性,反之亦然。如果你正在使用GET并且请求URI变得非常长,超过2KB,那么考虑使用POST而不是GET,否则URI可能会被服务器截断。优点:更好的可重复使用服务。缺点:难以发送二进制数据。

  1. Convert to String and send as parameter. On retrieval, convert back from String. JSON is a nice format for this. Google Gson offers possibilities to convert between fullworthy Java objects and JSON and vice versa. If you're using GET and the request URI gets pretty long, over 2KB, then consider using POST instead of GET, else the URI may be truncated by the server. Pros: better reuseable service. Cons: hard to send binary data.

另请参阅: 将JSON转换为Java

发送 multipart / form-data 使用 URLConnection Apache HttpComponents客户端,根据 RFC2388 并使用 Apache Commons FileUpload 在另一侧处理它。优点:标准规范,可以发送二进制数据。缺点:更多代码。

Send a multipart/form-data HTTP POST request using URLConnection or Apache HttpComponents Client as per RFC2388 and process it on the other side using Apache Commons FileUpload. Pros: standard specification, possible to send binary data. Cons: more code.

另见: 如何使用URLConnection

序列化 Java对象,将其原始写入使用 URLConnection#getOutputStream() rel =nofollow noreferrer> ObjectOutputStream 并从中检索它原始HttpServletRequest#getInputStream()并使用 ObjectInputStream 。优点:简单。缺点:不可重复使用,紧密耦合。

Serialize the Java object, write it raw to the URLConnection#getOutputStream() using ObjectOutputStream and retrieve it raw from the HttpServletRequest#getInputStream() and unserialize it using ObjectInputStream. Pros: easy. Cons: not reuseable, tight coupled.

另见: Object Streams 课程:序列化