Search code examples
spring-bootspring-mvcinterceptor

spring boot interceptor for specific api, should not be invoked for all the api's


2 api's were exposed in a spring boot controller class. I have a requirement to intercept only 1 api and SHOULD NOT intercept other api. Can someone assist how to do this?

Below is the code

public class HeaderValidationInterceptor extends HandlerInterceptorAdapter{
    
    private static final Logger logger = Logger.getLogger(HeaderValidationInterceptor.class);

    //before the actual handler will be executed
    public boolean preHandle(HttpServletRequest request, 
        HttpServletResponse response, Object handler)
        throws Exception {
        
        validateHeaderParam(request);
        request.setAttribute("startTime", startTime);
        
        return true;
    }
    
    }
    

Also I have a configuration class to add interceptor as below

Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

  @Autowired 
  HeaderValidationInterceptor headerValidationInterceptor;

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(headerValidationInterceptor)
    }
    
}

Controller class

@RestController
public class MyController {

    @Autowired
    private ICityService cityService;

    @GetMapping(value = "/cities")
    public List<City> getCities() {

        List<City> cities = cityService.findAll();

        return cities;
    }
    
    
@GetMapping(value = "/cities/{cityId}")
    public City getCityById(@PathVariable("cityId") String cityId) {

        City city = cityService.findCityById(cityId);

        return cities;
    }
}

Solution

  • Inside your interceptor, you can check the request URI for the endpoint you want to intercept.

    You can use a regular expression to match the URI. Following for /cities/{cityId} endpoint.

    if (request.getRequestURI().matches("(\\/cities\\/[a-zA-Z0-9]+\\/?)")) {
        validateHeaderParam(request);
        request.setAttribute("startTime", startTime);
    }
    

    I'm not sure what is that want to do in your interceptor, but for your example you can do this inside your controller as well. Like this,

    @GetMapping(value = "/cities/{cityId}")
    public City getCityById(@PathVariable("cityId") String cityId, HttpServletRequest request) {
    
        // Here you can use HttpServletRequest and do your validation
        // validateHeaderParam(request);
        // request.setAttribute("startTime", startTime);
        
        City city = cityService.findCityById(cityId);
        return cities;
    }