You need to configure HttpSessionListenerfor your application.
The interface is called onSessionDestroy, which is called when the session ends, and you can serialize directly.
To configure the listener, add to web.xml:
<listener>
<listener-class>com.example.app.session.MySessionListener</listener-class>
</listener>