How to configure spring interceptor to get called with every request

Viewed 2811

I want to configure my spring interceptor in such a way that with every request it should get called.

  • I am using interceptor in API-GATEWAY (Spring-Boot)
  • From API-GATEWAY I am calling other microservices.
  • The call's to other microservices from API-GATEWAY is working fine.
  • Other Services which I am calling are Node.js Service, on the other hand, my API-Gateway is in spring boot.
  • All the services (Node.js + Spring-Boot) are running on Docker Container.

I am facing an issue in Interceptor. I want to configure it in such a way that with every request it should be called the preHandle() and perform the operations that I have written in it.

I have notice one issue that I want to mention here.

If the services which I am calling is stopped (Not Running), Interceptor is working properly and giving me a response like somename-service not found. If the same services are running at this time Interceptor is not executed.

Here is my code snippet

@EnableEurekaClient
@SpringBootApplication
@EnableZuulProxy
@Configuration
public class Application extends WebMvcConfigurerAdapter {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Autowired
    private TokenValidateInterceptor tokenValidateInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(tokenValidateInterceptor).addPathPatterns("/**");


    }

Interceptor

@Component
public class TokenValidateInterceptor extends HandlerInterceptorAdapter {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        LOG.info("#### Starting TokenValidateInterceptor.preHandle ####");

        String apiKey = null;
        try {
            apiKey = request.getHeader("apikey");

            LOG.info("The request come with apikey ======" + apiKey);

            LOG.info("Actual apikey ======" + azureApikey);


}
3 Answers

First make a WebMvc Config class as shown below

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor());
    }

Create Request Interceptor i.e. MyInterceptor by extending HandlerInterceptorAdapter

public class MyInterceptor extends HandlerInterceptorAdapter{
    @Override
    public void postHandle(HttpServletRequest request, 
    HttpServletResponse response, 
    Object handler, 
    ModelAndView modelAndView) throws Exception {
        ......Write your business logic here...........}
}

for more information you can refer here

I think you should use HttpFilter in this case, it has doFilter method, just override that method and execute your code.

Related