Is Spring HandlerInterceptorAdapter postHandle guaranteed?

I currently have two interceptors that handle a similar function. I would like to combine them.

One interceptor is an access request logger that shows the logged in user, session ID, and requested URL.

Another interceptor is the process logger.

An access registrar, in order to register everything that needs to be registered, registers the request in the preHandle method. The idea is that no matter what happens after (i.e. Exceptions), an exact access request will be available.

However, the process logger, by its nature, must register the postHandle method.

To merge this functionality, I would have to move everything to one postHandle method. However, it seems that I might lose some logging if an exception occurs somewhere, especially one that has not yet been properly handled in the application code.

Are there any guarantees or descriptions of these considerations?

+6
source share
1 answer

You might consider merging the logic inside afterCompletion, which will be called even if the handler method throws an exception. Good online example

public class RequestProcessingTimeInterceptor extends HandlerInterceptorAdapter { private static final Logger logger = LoggerFactory .getLogger(RequestProcessingTimeInterceptor.class); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { long startTime = System.currentTimeMillis(); logger.info("Request URL::" + request.getRequestURL().toString() + ":: Start Time=" + System.currentTimeMillis()); request.setAttribute("startTime", startTime); //if returned false, we need to make sure 'response' is sent return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("Request URL::" + request.getRequestURL().toString() + " Sent to Handler :: Current Time=" + System.currentTimeMillis()); //we can add attributes in the modelAndView and use that in the view page } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { long startTime = (Long) request.getAttribute("startTime"); logger.info("Request URL::" + request.getRequestURL().toString() + ":: End Time=" + System.currentTimeMillis()); logger.info("Request URL::" + request.getRequestURL().toString() + ":: Time Taken=" + (System.currentTimeMillis() - startTime)); } } 
+6
source

Source: https://habr.com/ru/post/981201/


All Articles