RequestContextHolder.currentRequestAttributes()
拋出異常如何訪問從兒童或不同的線程HttpRequest對象在Spring MVC的Web應用程序
Exception in thread "Thread-4" java.lang.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.
at org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes(RequestContextHolder.java:131)
at com.sbicapsec.managerImpl.LoginmanagerImp$1.run(LoginmanagerImp.java:36)
at java.lang.Thread.run(Unknown Source)
我的代碼
@Override
public void adminLogin(AdminModel model) {
Thread t=new Thread(new Runnable() {
@Override
public void run() {
final ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder
.currentRequestAttributes();
final HttpServletRequest request = attr.getRequest();
}
});
t.start();
HomePage.nc.AdminLogin(HomePage.nc, model.getUserName(), model.getPassword());
}
的web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>loginproject</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>cors</filter-name>
<filter-class>com.sbicapsec.filter.SimpleCORSFIlter</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<display-name>RequestContextListener</display-name>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
</web-app>
我想這樣做是因爲從我的經理班,我正在調用包含第三方罐子的方法。但是這些方法在不同的線程中調用。我想將這些方法的響應放在會話屬性中,以便我可以在自己的線程中使用它。
從呼叫請求處理線程的「經理類的方法」,那麼。如果你已經這麼做了,那你爲什麼不把你的請求對象傳遞給你的runnable,保證以靜態線程方式獲取它? 作爲digresion的問題,您應該寧願使用開始新線程的線程池insteed。 – Antoniossss
在新的線程中你沒有請求。我猜你不能這樣做,操作在一個新線程 –
@Antoniossss那些不是我的methods.I沒有訪問這些methods.When我調用這些方法,它在內部創建新的線程。然後 –