春季启动:在RestController中访问拦截器的数据

时间:2019-05-03 12:18:39

标签: spring spring-boot spring-mvc interceptor

我有一个简单的SpringBoot(2.1.4)应用程序,该应用程序使用Interceptor对每个传入请求进行一些检查。拦截器专门创建一个对象,然后(在preHandle()之后)需要在我的RestController中访问该对象。

更具体地说,这是我的拦截器:

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;
    }
}

我需要在控制器中访问x

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

        // access object x HERE!

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

我现在的问题是:我如何在控制器中访问X的上述实例?

1 个答案:

答案 0 :(得分:1)

您可以在拦截器中使用ServletRequest#setAttribute

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;
  }
}

以及Controller中相应的@RequestAttribute

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