• RequestContextHolder:持有上下文的Request容器
  • 通过RequestContextHolder的静态方法可以随时随地取到当前请求的request对象
// 获取相关对象
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

// 底层实现:request.getAttribute("userId");
String userId = (String) requestAttributes.getAttribute("userId",RequestAttributes.SCOPE_REQUEST);

// 底层实现:session.getAttribute("userId");
String userId = (String) requestAttributes.getAttribute("userId",RequestAttributes.SCOPE_SESSION);

// 或者转成具体对象
HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
HttpServletResponse response = ((ServletRequestAttributes) requestAttributes).getResponse();
HttpSession session = request.getSession();

参考:

  1. RequestContextHolder分析    https://blog.csdn.net/asdfsadfasdfsa/article/details/79158459 
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐