views:

72

answers:

2

What's the recommended approach to intercepting session.getAttribute() and session.setAttribute()? This is in a Spring based application so something AOP-based would be great. I'd like to avoid having to override core Tomcat classes if possible.

Update: I want to store the actual serialized attributes in a web service.

+3  A: 

I am not familiar with AOP or Spring (or Tomcat). :) But I am familliar with Java

The way I do it is set up a filter, and replace the request variable with my own object

request = new MyRequest(request);

Then override getSession() and getSession(boolean) to return an instance of MySession

the javax.servlet.HttpServletRequest and javax.servlet.HttpSession classes are Java EE standard and not Tomcat specific.

cjavapro
Damn good idea, put a facade around the request itself...
Abdullah Jibaly
This was my first answer that got up rating. I am watching it stay neck and neck with Matt's answer :)
cjavapro
Looks like this approach is cleaner for my use case, thanks.
Abdullah Jibaly
+3  A: 

You could implement your own session org.apache.catalina.Manager and swap it into Tomcat's configuration, although the interface looks rather lengthy - so perhaps look at extending ManagerBase or StandardManager first.

As an alternative, register a HttpSessionAttributeListener to be notified whenever a session attribute is added/removed/updated. This won't change the default storage mechanism - the session data will still be kept in-memory as well - but it would let you persist the data with an alternative mechanism as well.

matt b
The first approach you mentioned is what I did first, unfortunately I may not be able to modify core Tomcat config in this instance. The AttributeListener approach looks interesting and not too invasive, I'll definitely give that a try.
Abdullah Jibaly
@Abdullah, you should be able to configure a different Manager by editing conf/server.xml.
matt b
But don't the class files (or jar) need be in TOMCAT_HOME/lib? I don't think I have access to that folder, is there a way around that?
Abdullah Jibaly
I think you are correct that any new Manager you configure Tomcat to use would have to be available on the server-level classpath. I'm assuming that if you want to be able to change where session-level data is being stored you'd have access to re-configure things like this. If not, the listener might be your best approach.
matt b
Correction - you can configure details about which Manager to use either at the server-level or also at the context (read: application) level as well: http://tomcat.apache.org/tomcat-6.0-doc/config/context.html
matt b
Cool, worth giving a try, thanks!
Abdullah Jibaly