I have a simple SpringBoot (2.1.4) app that uses an Interceptor to do some checks on every incoming request. The interceptor specifically creates an object, which I would then (after preHandle()) need to access in my RestController.

To be more specific, this is my Interceptor:

public class MyInterceptor extends HandlerInterceptorAdapter {
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) throws Exception {}

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {}

    @Override
    public boolean preHandle(HttpServletRequest requestServlet, HttpServletResponse responseServlet, Object handler) throws Exception {

        X x = new X();
        x.computeCureForCancerAndStoreItInThisInstance();

        return true;
    }
}

And I need to access x in my controller:

@RestController
@RequestMapping("/")
public class MyController {
    @GetMapping("/")
    @ResponseBody
    public ResponseEntity getCureForCancer() {

        // access object x HERE!

        return new ResponseEntity<String>("ok", HttpStatus.OK);
    }
}

My question now would be: how to I access said instance of X in my Controller?

1 Answers

1
caco3 On

You can use ServletRequest#setAttribute in the interceptor:

public class MyInterceptor extends HandlerInterceptorAdapter {
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    // create x
    request.setAttribute("com.acme.x", x);
    return true;
  }
}

And corresponding @RequestAttribute in Controller:

public ResponseEntity myHandler(@RequestAttribute("com.acme.x") X x)