Java RequestContextHolder、currentRequestAttributes()和getRequestAttributes()的这些方法之间有什么区别?
我试图使用Java RequestContextHolder、currentRequestAttributes()和getRequestAttributes()的这些方法之间有什么区别?,java,spring,spring-boot,httprequest,Java,Spring,Spring Boot,Httprequest,我试图使用RequestContextHolder,在这个类中,我们有两个方法currentRequestAttributes()和getRequestAttributes()这些方法之间的区别是什么 我看到这两种方法有相同的含义,那为什么我们有两种方法呢 我的要求是我想在我的应用程序的一个类中设置当前处理请求中的一个属性,并在同一应用程序的另一个类中使用它来处理相同的请求,因此我考虑使用RequestContextHolder,但是我发现这两种方法有着相同的意义,哪一种对我的问题更有意义 注意
RequestContextHolder
,在这个类中,我们有两个方法currentRequestAttributes()
和getRequestAttributes()
这些方法之间的区别是什么
我看到这两种方法有相同的含义,那为什么我们有两种方法呢
我的要求是我想在我的应用程序的一个类中设置当前处理请求中的一个属性,并在同一应用程序的另一个类中使用它来处理相同的请求,因此我考虑使用RequestContextHolder
,但是我发现这两种方法有着相同的意义,哪一种对我的问题更有意义
注意:使用该类的原因是我不想将类中计算的标志一直传递到spring boot应用程序的起始类,因为如果我想传递,那么我需要更改该调用堆栈中的所有方法签名,可能需要更改太多的方法签名,由于这个标志是根据每个请求计算的,所以我决定使用这个类
RequestContextHolder
这是getRequestAttributes的源代码
和属性
似乎currentRequestAttributes正在首先调用getRequestAttributes。currentRequestAttributes检查请求是否在JSF环境中,如果在JSF环境中,则返回FacesContext参数。在您的情况下,您只需要自己设置一个参数并在其他地方使用它,所以getRequestAttributes方法应该完成您的工作 您可以阅读源代码:
currentRequestAttributes()
只是getRequestAttributes()
+if(getRequestAttributes()==null)
回退到FacesRequestAttribute工厂。GetFacesRequestAttribute()代码>+如果null抛出exception@varren,感谢您指向有用的链接,现在我知道infact currentRequestAttributes()正在调用getRequestAttributes(),对于纯spring启动应用程序(而不是JSF应用程序),我们最好只调用getRequestAttributes(),再次感谢您的帮助。是的,您提到了correct和varren,向我指出了那个方向,谢谢你的密码Doğukan Zengin
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/DispatcherPortlet: " +
"In this case, use RequestContextListener or RequestContextFilter to expose the current request.");
}
}
return attributes;
}