Search code examples
javaservlets

Java: How to get intercept on Filter after it returns from the controller


The filter is triggered for incoming request but not for the responses.

Spring Interceptors gives the functionality to handle the request before and after it hits the controller. I want to build something similar so, I can handle responses globally:

public class ServiceSessionManagementInterceptor implements Filter{

@Override
public void init(FilterConfig filterConfig) throws ServletException {
    // TODO Auto-generated method stub
    
}

@Override
public void doFilter(ServletRequest request, ServletResponse response,  FilterChain chain) throws IOException, ServletException {
    // TODO Auto-generated method stub
    Map<String, String[]> maps = request.getParameterMap();
    
    System.out.println("test");
chain.doFilter(request, response);  
}

@Override
public void destroy() {
    // TODO Auto-generated method stub
    
}

}


Solution

  • The doFilter() is where magic happens. Whatever you put before it will be executed before the servlet and everything you put after it will be executed after the servlet service() method returns (including a forward/include, etc.).

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,  FilterChain chain) throws IOException, ServletException {
    
        System.out.println("before");
        chain.doFilter(request, response);  
        System.out.println("after");
    }
    

    This way you could wrap the ServletRequest and ServletResponse objects with your own implementations to add functionality, ex: compression.

    Note that a Spring Interceptor is called before and after the handler method gets executed. A servlet Filter gets executed before and after a Servlet.