How can I maintain state between Java servlets?

Situation

I have several servlets with one responsibility that take a request, do their job, respond and execute โ€” in these cases, you donโ€™t need to maintain state.

However, I have a โ€œPlain old Java objectโ€ that maintains status information based on the actions that the user initiated on the client that I would like to make available to my servlets on request. I would like to make a single instance of this object available and don't need / don't want to support multiple shared instances.

Side note: this data is temporary (you need to save it for 10 minutes) and not quite what I would like to save in the database.

Question

I supported a shared instance of an object with JSP before, but in this case the servlet makes more sense. So my question is, how can I appropriately manage the lifetime of this stateful object and can share it between servlets without saving by HTTP requests or some other mechanism?

In other words, if it is a non-web application, servlets without state preservation will be objects to which I would delegate the task, and stateful objects will support the results.

I looked at the ServletContext, but I do not quite understand the purpose of this, to know if I need it.

+4
source share
2 answers

Perhaps I misunderstand your question, but have you thought about the session?

[edit] So you really need a session.

You can use a session, for example, as follows:

public class TestServlet extends HttpServlet { .... protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getSession().setAttribute("test", new Date()); } .... } 

The object you store there must be serializable by IIRC.

If you use the eclipse or netbeans code scrolling function, and javadoc should indicate a way to use more advanced materials.

+13
source

If you can save the entire servlet under the same webapp (context), you can save the session in ServletContext or HttpSession.

If you need multiple instances, ServletContext / HttpSession will not work. I suggest storing sessions in memcached.

In any case, you need to manage the session timeout yourself.

+1
source

All Articles