0

I need to intercept every request made to a Spring boot application, read the content in the Header, the Body, parsing then and map few fields in the JSON, when it is possible, before to store in a specific table of the application.

I've been trying to use the RequestContextFilter class like it is described here but it is not working for me. When I make a request to /v1/account/ endpoint, for example, nothing is printed in the log and nothing happen if I try to debug. I believe I am not doing right.

I really appreciate any idea, example. This project is my personal example project but I will have to apply this solution in Spring 4.3.x.

I created this filter class as following here but I also shared the project here.

@Configuration
public class AuditingRequestContextFilter {
    @Bean
    public FilterRegistrationBean contextFilterRegistrationBean() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        RequestContextFilter contextFilter = new RequestContextFilter();
        registrationBean.setFilter(contextFilter);
        registrationBean.setOrder(1);
        System.out.println("AuditingRequestContextFilter.contextFilterRegistrationBean() - registrationBean: " + registrationBean);
        return registrationBean;
    }
}

I also added the spring.factories but I don't know if it is really necessary.

The Spring documentation only provides this content but please, someone share a simple example to make the filter be called every time any request is made to any controller in the application?

1 Answers1

1

I need to intercept every request made to a Spring boot application

One simple way to achieve this by implementing the Servlet Filter.

@Component
public class RequestFilter implements Filter {
  
  @Override
  public void init(FilterConfig config) throws ServletException {}
     
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
      throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    // TODO: Here you can read the request content as per your need from httpRequest object
    filterChain.doFilter(request, response);
  }
  
  @Override
  public void destroy() {}
  
}
b.s
  • 2,409
  • 2
  • 16
  • 26