The usual way to handle this is as follows:
(1) When the user logs in, put their user ID (or some similar token) into the session.
(2) When the user logs out, remove that token from the session and invalidate the session.
(3) Use a
servlet filter which checks that there is an active session and that it contains a user ID token. If not, then redirect to the login page.
Note that this is independent of the number of seconds it takes for an inactive session to become invalid. Note also that nothing happens when the session becomes invalid; the is-the-user-logged-in decision only takes place when the user sends a request.