可以在Java, SpringBoot 的任意代码位置,获取到请求信息,例如下面的代码,可以获取到 Request Head信息。
如果在Controller线程外,新开线程中进行设置,例如TheadPool中调用,那么必须在 ExecutorServices.submit()的开始设置 RequestContextHolder.setRequestAttributes(),例如:
- ServletRequestAttributs attributes = RequestContextHolder.getRequestAttributes();
- executor.submit(
- () -> {
- RequestContextHolder.setRequestAttributes(attributes);
- // ..... 做其他事情
- RequestContextHolder.resetRequestAttributes();
- }
- );
否则可能报错误!
✘
No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
- HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
-
- Enumeration<String> headerNames = request.getHeaderNames();
- while (headerNames.hasMoreElements()) {
- String headerName = headerNames.nextElement();
- String headerValue = request.getHeader(headerName);
- System.out.println("Header: " + headerName + " = " + headerValue);
-
- }
-
- String requestURI = request.getRequestURI();
- String method = request.getMethod();
- System.out.println("Request URI: " + requestURI);
- System.out.println("Request Method: " + method);