In our Java web application which uses Struts 1, we have a lot of code that essentially does this:
HttpSession session = httpServletRequest.getSession();
MyObject myObject = session.getAttribute(MY_OBJECT_KEY);
//code that mutates myObject - setting properties or whatever
session.setAttribute(MY_OBJECT_KEY, myObject);
My question: Is the last line, session.setAttribute(..) necessary? It seems pointless to me – ‘myObject’ and ‘session.getAttribute(..)’ refer to the same location in memory, right? So re-setting the attribute in the session should not be required? Does this do anything I am not aware of? The object does not implement HttpSessionBindingListener which is mentioned in the documentation.
I feel like I need to double check because this is done all over this app and I certainly don’t want to break anything just because I am cleaning up code. Thanks
It depends what you mean by “mutate”. If “mutate” in this context means you changed properties, but not the instance, then no, you don’t need to
setAttributeat the end.myObjectis a reference to the underlying object. The session has its own reference. They both point to the same underlying object, so you’d be changing properties on the same instance.Now, if you do
myObject = new MYObject();THEN you need to pass the new object to the session. In this case, your reference
myObjectnow points to a different instance than the session’s reference.Note, why not write a unit test and test it out?