I have implemented a Servlet, and a PHP site is accessing that Servlet to retrieve data. I'm wondering what is the best method to store a session variable, or whether I should store it at all.
Variables which need to be stored include an ArrayList, and other objects.
I've thought through about 3 possibilities:
(1) Implement the HttpSessionListener, and store each session (when it's created) into a static SessionMap. Then delete the session once it is destroyed.
(2) Store everything in JSON. So I'll have to serialize/deserialize each Object and pass it back and forth. (I have a list of items in each ArrayList/Object I want to keep track of between user clicks.)
(3) Store the information in MongoDB (just to pick one), using the SessionID as the primary key.
What do you guys think?
I rather like a combination of all three.
I don't believe it has to be an exclusive choice.
The HttpSessionListener
is unnecessary here. All you basically need to do in the servlet is:
List<String> links = (List<String>) request.getSession().getAttribute("links");
if (links == null) {
links = new ArrayList<String>();
request.getSession().setAttribute("links", links);
}
links.add(request.getParameter("link"));
The attributes will be garbaged anyway when the session get destroyed.
JSON only adds unnecessary overhead and a database is only beneficial when there's not much memory space in webserver (however, DB's in turn also eats memory to a certain degree).
I only wonder how you think to maintain the same servlet session from PHP on. This would involve invoking the servlet using JSESSIONID attribute in URL (bad idea) or a PHP script with curl acting as a proxy (why not just doing it all in PHP?). Or is it running on the same domain? Or are you using Quercus to run PHP on a Java servletcontainer?