The topic title conflicts with the question in the message. You're asking in the title how to hook on the end of session, but in the message you're asking how to hook on the end of request. Those are two entirely different scopes. The session lives from the first request a client ever made for which no HttpSession
object is been created until the time that it times out or got invalidated. The request lives from the first click/bookmark/addressbar-invocation of the client until the associated response has been fully committed and sent.
Let's assume that you actually meant request as your're already talking about the benefit of filters to hook some code before the request is been processed. You probably didn't realize that you can use the very same Filter
to hook some code after the request is been processed. All you need to do is to just put the appropriate code after the FilterChain#doFilter()
.
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
// You can do here stuff BEFORE the request is been processed further.
chain.doFilter(request, response);
// You can do here stuff AFTER the request is been processed.
}
You probably expected that the FilterChain#doFilter()
kind of automagically exits the method block immediately, like as many starters would expect that for for example HttpServletResponse#sendRedirect()
and consorts. This is untrue, it's the return
statement and/or just the end of method block which does that, aside from exceptions/errors. Those methods are just invoked the usual Java way and does nothing special.