0

I am using spring boot version 1.3.3. With the embedded tomcat.

For each web requests I would like to know how intercept a web request and do some custom code then continue on with the request.

My hunch is that I would override some default servlet bean or method? I don't know much about this.

So to make the question specific. For every web request how would I do the following code

@Override  
public void someGenericWebParentRequest(Servlet servletRequest){
   log.info("custom log called");
   MDC.put("host-name", System.getenv("HOSTNAME"));  // kibana hostname filter added

   // whatever code you fancy etc :-)       

   return servletRequest;  // continues onto web target controller 
}
Robbo_UK
  • 11,351
  • 25
  • 81
  • 117

1 Answers1

2

You can use Servlet Filter and add intercept requests in doFilter(). To add it into Spring Context, add @Component.

Refer this sample.

@Component
public class SecurityFilter implements Filter{
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
         //you can intercept request and response here
        System.out.println("###### security filter ");
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
Sundararaj Govindasamy
  • 8,180
  • 5
  • 44
  • 77
  • this works thanks. accepted the answer. I have taken a look around on the filter is this like a kind of firewall for http requests into the spring app? – Robbo_UK Oct 07 '16 at 09:33
  • Yes, kind of, but http requests to Servlet ( not only spring app), please remember In spring there is default servlet called dispatcherservlet – Sundararaj Govindasamy Oct 07 '16 at 11:50