You can test expired sessions by checking that HttpServletRequest#getRequestedSessionId() does not return null (this means the client sent a session cookie and therefore assumes that the session is still valid) and HttpServletRequest#isRequestedSessionIdValid() returns false (which means that the session has expired on the server side).
In a nut:
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; HttpSession session = request.getSession(false); if (request.getRequestedSessionId() != null && !request.isRequestedSessionIdValid()) { response.sendRedirect(request.getContextPath() + "/sessionexpired.jsp"); } else if (session == null || session.getAttribute("user") == null) { response.sendRedirect(request.getContextPath() + "/login.jsp"); } else { chain.doFilter(request, response); } }
No need to worry about extra cookies. Print this Filter on a url-pattern protected by secure pages (and thus excluding session pages and login pages!).
Remember to disable browser caching of the page on protected pages, otherwise the web browser will load them from the cache when you return to the browser history, instead of sending a new request to the server. You can achieve this by doing the following in the same filter before calling Chain#doFilter() .
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1. response.setHeader("Pragma", "no-cache"); // HTTP 1.0. response.setDateHeader("Expires", 0); // Proxies.
Balusc
source share