Share Java classes between war files in Tomcat?

2019-02-24 10:23发布

I am using Tomcat 7 as a servlet container and I have two war files (two projects in Eclipse). The problem is, that I want to share classes between both deployed war files. But this is not possible with Tomcat / Servlet specifications as far as I know. Both deployed web applications seems to be are isolated from each other.

So I read, I am a newbie, from JBoss as an application server in which I can deploy ear files (so I can put multiple war files into it) and then I can share classes between them?

So my question: Do you agree with my statement, is it possible to do this with JBoss? And do I have to make changes or can I put easily both in an ear file and deploy it with JBoss and it will work?

Best Regards, Tim.

1条回答
疯言疯语
2楼-- · 2019-02-24 11:10

There are 2 easy options. Both require you to define the shared classes in a separate project (JAR), let's call it SHARED. Now, when it comes to deployment you have 2 options:

  1. copy SHARED.jar to Tomcat's lib folder and you're done.
  2. reference SHARED.jar in your WebApp, when exporting your WAR from eclipse the tooling will create a JAR, place it in WebApp's WEB-INF/lib folder, and create the WAR (see screenshot).

If you go with option #1 it is important to understand that the same classes are shared between the WebApp classloaders (Tomcat system classloader), so you'd go with this option only if you want to share state between different WebApps (e.g. Singletons).

BTW: The screenshot is made using Eclipse 3.6 + WTP...

enter image description here

查看更多
登录 后发表回答