|
| 1 | +package org.baeldung.web.interceptor; |
| 2 | + |
| 3 | +import javax.servlet.http.HttpServletRequest; |
| 4 | +import javax.servlet.http.HttpServletResponse; |
| 5 | +import javax.servlet.http.HttpSession; |
| 6 | + |
| 7 | +import org.slf4j.Logger; |
| 8 | +import org.slf4j.LoggerFactory; |
| 9 | +import org.springframework.beans.factory.annotation.Autowired; |
| 10 | +import org.springframework.security.core.context.SecurityContextHolder; |
| 11 | +import org.springframework.web.servlet.ModelAndView; |
| 12 | +import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; |
| 13 | + |
| 14 | +public class SessionTimerInterceptor extends HandlerInterceptorAdapter { |
| 15 | + |
| 16 | + private static Logger log = LoggerFactory.getLogger(SessionTimerInterceptor.class); |
| 17 | + |
| 18 | + private static final long MAX_INACTIVE_SESSION_TIME = 5 * 10000; |
| 19 | + |
| 20 | + @Autowired |
| 21 | + private HttpSession session; |
| 22 | + |
| 23 | + /** |
| 24 | + * Executed before actual handler is executed |
| 25 | + **/ |
| 26 | + @Override |
| 27 | + public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) |
| 28 | + throws Exception { |
| 29 | + log.info("Pre handle method - check handling start time"); |
| 30 | + long startTime = System.currentTimeMillis(); |
| 31 | + request.setAttribute("executionTime", startTime); |
| 32 | + if (UserInterceptor.isUserLogged()) { |
| 33 | + session = request.getSession(); |
| 34 | + log.info("Who is logged in: " + SecurityContextHolder.getContext().getAuthentication().getName()); |
| 35 | + log.info("Time since last request in this session: " |
| 36 | + + (System.currentTimeMillis() - request.getSession().getLastAccessedTime()) + " ms"); |
| 37 | + if (System.currentTimeMillis() - session.getLastAccessedTime() > MAX_INACTIVE_SESSION_TIME) { |
| 38 | + log.warn("Logging out, due to inactive session"); |
| 39 | + SecurityContextHolder.clearContext(); |
| 40 | + request.logout(); |
| 41 | + response.sendRedirect("/spring-security-rest-full/logout"); |
| 42 | + } |
| 43 | + } |
| 44 | + return true; |
| 45 | + } |
| 46 | + |
| 47 | + /** |
| 48 | + * Executed before after handler is executed |
| 49 | + **/ |
| 50 | + @Override |
| 51 | + public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, |
| 52 | + final ModelAndView model) throws Exception { |
| 53 | + log.info("Post handle method - check execution time of handling"); |
| 54 | + long startTime = (Long) request.getAttribute("executionTime"); |
| 55 | + log.info("Execution time for handling the request was: " + (System.currentTimeMillis() - startTime) + " ms"); |
| 56 | + } |
| 57 | +} |
0 commit comments