7

I have two web applications say App1 and App2. I want to call a servlet which is in App2 from a servlet in App1. I'm using URLConnection for this. I'm able to pass parameters to the servlet in App2 also and I'm also able to receive response from the servlet as string. But I want to send java objects from the servlet in App2 and receive them in servlet of App1. How to achieve this?

BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
Venkatesh
  • 71
  • 1
  • 2

2 Answers2

10

Depends.


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");

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.


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

  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.

    See also: Converting JSON to Java.

  2. 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.

    See also: How to use URLConnection.

  3. 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.

    See also: Object Streams and Lesson: Serialization.

Community
  • 1
  • 1
BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
1

Use Serialization

Instead of sending HTML you'll send objects streams.

Just, be aware, to add extra security, you don't want to some external source inject poisoned objects into your calls.

OscarRyz
  • 184,433
  • 106
  • 369
  • 548