Springboot : RequestContextHolder

Springboot : RequestContextHolder,第1张

Springboot : RequestContextHolder 前言
  • springboot 2.0.0.RELEASE
  • sping-web 提供了 RequestContextHolder 。RequestContextHolder 让开发者可以在请求的任意位置获取到 request、response、session 等。
  • 因 RequestContextHolder 是 sping-web 提供的,所以 springboot 中也可以使用。
获取请求参数
RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
//RequestAttributes requestAttributes =  RequestContextHolder.getRequestAttributes();

//获取请求参数
String str = (String) requestAttributes.getAttribute("name", RequestAttributes.SCOPE_REQUEST);
从SESSION取值
RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();

//从session里面获取对应的值
String str = (String) requestAttributes.getAttribute("name", RequestAttributes.SCOPE_SESSION);
获取request、response、session
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
HttpServletResponse response = attributes.getResponse();
HttpSession session = attributes.getRequest().getSession();
getRequestAttributes vs currentRequestAttributes
	
	@Nullable
	public static RequestAttributes getRequestAttributes() {
		RequestAttributes attributes = requestAttributesHolder.get();
		if (attributes == null) {
			attributes = inheritableRequestAttributesHolder.get();
		}
		return attributes;
	}
	
	public static RequestAttributes currentRequestAttributes() throws IllegalStateException {
		RequestAttributes attributes = getRequestAttributes();
		if (attributes == null) {
			if (jsfPresent) {
				attributes = FacesRequestAttributesFactory.getFacesRequestAttributes();
			}
			if (attributes == null) {
				throw new IllegalStateException("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.");
			}
		}
		return attributes;
	}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5081857.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-16
下一篇 2022-11-16

发表评论

登录后才能评论

评论列表(0条)

保存