Kidburla Kidburla - 5 days ago 7
Java Question

Can I cause a method to be triggered if the session ID is changed?

We have a method triggered in case the session ID gets changed. This method essentially allows our logger to pick up the change as soon as it happens, so any logging output is now against the new session ID.

In servlet API 3.0 and earlier we used

HttpSessionListener
whose
sessionCreated
method ran whenever the session ID was updated. This is because in 3.0 and earlier, the only way to change the session ID is to create a new session.

Servlet API 3.1 introduced the
changeSessionId
method. This does not cause the session to be re-created, so the
HttpSessionListener
does not get called. However, it is another way to change the session ID. So is there any similar way to cause a method to be triggered in case the session ID is changed?

Answer

Since Servlet API 3.1 you can use HttpSessionIdListener:

Implementations of this interface are notified when an HttpSession's ID changes. To receive notification events, the implementation class must be configured in the deployment descriptor for the web application, annotated with WebListener or registered by calling an addListener method on the ServletContext.