Home > database >  Intercept header & call service before every endpoint
Intercept header & call service before every endpoint

Time:12-18

I have a usecase where every single HTTP request to my SpringBoot app will contain an id in a header. I need to call an internal service to retrieve informations stored in my database based on that id; those informations will then be used inside my services called by the RestControllers.

I've thought about using Interceptors, but even though those will allow me to call my service and retrieve informations in the DB, there's no way in my knowledge to forward that object to my business services. Another path I've explored is through AOP. But while you can inside your aspects retrieve informations of the method that calls you, I don't think you can access data retrieved by the aspect inside the annotated method.

Is there any way to do this properly without using @RequestHeader and calling my service by hand in every single RestController's method (thus duplicating a ton of code) ?

Thanks !

CodePudding user response:

but even though those will allow me to call my service and retrieve informations in the DB, there's no way in my knowledge to forward that object to my business services

You can use the HttpServletRequest request which has http request scope, meaning a new object is created for each http request the client makes in the server. You can enrich it with other information through each interceptor so it will contain it as attributes when it is passed to the final controler method.

Use the following method of the HandlerInterceptor, which will be called before the spring business method is invoked.

boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)

Then inside this method you can set the value you want as attribute in the request object.

boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
    ... call external api and fetch some value....
    ... Object myObj = apiCall...
    request.setAttribute("myObj", myObj);
    return true;
}

Then in your spring controller you can access this attribute you have set before.

    @GetMapping(path = "/{mypath}")
    public void getRequest(HttpServletRequest request){

       Object myObj = request.getAttribute("myObj");
        if (myObj != null) {
          //you have myObj accessible here!
        }
   }
  • Related