Passing data between two servlets

2020-07-27 06:30发布

问题:

I have two servlets running on the same Tomcat server, and I need to pass data from an instance of one servlet to the corresponding instance of the other servlet. It appears as though I can do this by doing something like this:

getServletContext().getContext("/path").setAttribute("varName", variable)

And I should likewise be able to receive it from the other servlet by using getAttribute. But, here is my question:

How does the other servlet know when this attribute has been set? The data can come in at any point in time, and multiple times. So how do I "notify" the other servlet that there is now data waiting for it to grab?

Thanks,

Eric

EDITED:

Here is some more insite into what I am trying to do: I am trying to build a chat program with two different apps. There is the client, which can send messages to another app, the chat receiver app. I am using Vaadin for the front-end. The chat receiver app contains two servlets: another Vaadin application, and a basic servlet to receive messages from the client app (this part is already working). Now I want to relay that to the Vaadin application of the chat receiver app, which is in the same war file as the servlet that is receiving the messages. Hopefully that clears things up. Let me know if you think the Vaadin forums would be a better place to post this question. Thank you for your help, I am primarily a core java programmer, so I am pretty confused. I really appreciate it!

回答1:

The only mechanism to call a servlet is by issuing an HTTP request. Also, only the servlet container is allowed to call your servlets, handling their lifecycle.

This means you can set some servlet context attribute in one servlet and then wait for user to call the second servlet - which will see the global value. You cannot call one servlet from another.

Not sure what you want to achieve. Maybe forwarding/redirecting from first servlet to the second one would be enough?

request.setAttribute("varName", variable);
getServletContext().getRequestDispatcher("servlet2").forward(request,response);

Variable will be accessible in servlet2 via:

request.getAttribute("varName");

BTW your code is unnecessarily complex and error prone, try this:

getServletContext().setAttribute("varName", variable);