我正在尝试理解Tomcat中的线程。我正在使用一个遗留的JSP应用程序,该应用程序广泛使用ThreadLocals(在应用程序启动时通过servlet过滤器初始化)。我想将应用程序转换为Spring MVC,但我需要逐步完成,因为它是一个非常大的应用程序。
我无法从Spring MVC控制器访问存储在ThreadLocal中的数据。
I now understand that I cannot access the data stored in a ThreadLocal in a different thread.
有人可以解释Tomcat在创建新线程时的行为吗?
为了演示我的问题,我创建了一个带有一个servlet过滤器,一个“标准”JSP,一个Spring控制器和一个“Spring view”JSP的简单应用程序。每个组件都包含以下内容:
System.out.println("Spring JSP *** : " + Thread.currentThread().getName());
使用Maven(tomcat7:run)运行Web应用程序并在JSP和Spring视图之间单击,我得到类似的内容:
Servlet Filter *** : http-bio-8080-exec-1
JSP *** : http-bio-8080-exec-1
Servlet Filter *** : http-bio-8080-exec-3
Spring Controller *** : http-bio-8080-exec-3
Spring JSP *** : http-bio-8080-exec-3
Servlet Filter *** : http-bio-8080-exec-4
JSP *** : http-bio-8080-exec-4
Servlet Filter *** : http-bio-8080-exec-5
Spring Controller *** : http-bio-8080-exec-5
Spring JSP *** : http-bio-8080-exec-5
Servlet Filter *** : http-bio-8080-exec-6
JSP *** : http-bio-8080-exec-6
Servlet Filter *** : http-bio-8080-exec-7
Spring Controller *** : http-bio-8080-exec-7
Spring JSP *** : http-bio-8080-exec-7
Servlet Filter *** : http-bio-8080-exec-8
JSP *** : http-bio-8080-exec-8
Servlet Filter *** : http-bio-8080-exec-9
Spring Controller *** : http-bio-8080-exec-9
Spring JSP *** : http-bio-8080-exec-9
Servlet Filter *** : http-bio-8080-exec-10
JSP *** : http-bio-8080-exec-10
Servlet Filter *** : http-bio-8080-exec-10
Spring Controller *** : http-bio-8080-exec-10
Spring JSP *** : http-bio-8080-exec-10
Servlet Filter *** : http-bio-8080-exec-10
JSP *** : http-bio-8080-exec-10
Servlet Filter *** : http-bio-8080-exec-10
Spring Controller *** : http-bio-8080-exec-10
Spring JSP *** : http-bio-8080-exec-10
正如您所看到的,最初创建了几个不同的线程,然后Spring和JSP / Filter之间的线程使用趋向于汇聚到单个线程。
我需要Filter,JSP和Spring MVC在同一个线程中共享数据。 解决方法是什么?