Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can state be maintained between Java Servlets?

Situation

I have a few single-responsibility Servlets that take a request, do their job, respond, and are done -- no state need be maintained in these cases.

However, I have I "Plain Old Java Object" that maintains state information based on actions the user has initiated on the client that I would like to make available upon request to my Servlets. I would like to make a single instance of this object available and do not need/want to maintain multiple, shared instances.

Side Note: This data is transient (need to keep it for 10 minutes maybe) and not really something I would like to keep in a database.

Question

I have maintained a shared instance of of an object with JSP before, but in this, case a Servlet makes more sense. So, my question is how do I appropriately manage the lifetime of this object that maintains state and can share it among stateless Servlets via HTTP requests, or some other mechanism?

Put another way, if this were an non-web application, the stateless Servlets would be objects I would delegate a task to and the stateful object would maintain the results.

I have looked into ServletContext, but I don't fully understand the purpose of this to know if this is what I need.

like image 859
bn. Avatar asked Dec 09 '22 19:12

bn.


2 Answers

Maybe I am understanding your question wrong, but have you thought of the session?

[edit] So you really need the session.

You can use the session for example this way:

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

The object that you store there, needs to should be serializable IIRC.

If you use eclipse or netbeans the code-insight feature and the javadoc should lead you the way on how to use it for more advanced stuff.

like image 131
Patrick Cornelissen Avatar answered Dec 20 '22 22:12

Patrick Cornelissen


If you can keep all the servlet under the same webapp (context), you can store session into ServletContext or HttpSession.

If you need multiple instances, ServletContext/HttpSession is not going to work. I would suggest storing sessions in a memcached.

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

like image 37
ZZ Coder Avatar answered Dec 21 '22 00:12

ZZ Coder