Single web application on one Java EE server with different datasouces (Tomcat context.xml)

22.04.2016 13:46:54

My friend has an interesting problem: His application will be deployed multiple times on a single Java EE server, but every instance must use different database. In the last post I presented one solution. Another approach is to set things up on the server (preferably using JNDI Resource) so that you don't have to change the application at all. Thanks Radek and Csaba for pushing me to write about it.

Anyway, the configuration on the server is different for each Java EE server, obviously :-) In this post I will cover Tomcat, which is the most popular Java EE server (even though it's not a full-fledged Java EE server). You will have one WAR file: c:/your_application/app.war. And two XML files: [tomcat]/conf/Catalina/localhost/app1.xml and [tomcat]/conf/Catalina/localhost/app2.xml

app1.xml:

<?xml version='1.0' encoding='utf-8'?>
<Context docBase="c:/your_application/app.war" reloadable="true">
	<Resource name="jdbc/app" auth="Container"
          type="javax.sql.DataSource" driverClassName="org.postgresql.Driver"
          url="JDBC_URL" username="USERNAME" password="PASSWORD" 
          maxActive="20" maxIdle="10" maxWait="-1"/>
</Context>

app2.xml:

<?xml version='1.0' encoding='utf-8'?>
<Context docBase="c:/your_application/app.war" reloadable="true">
	<Resource name="jdbc/app" auth="Container"
          type="javax.sql.DataSource" driverClassName="org.postgresql.Driver"
          url="JDBC_URL_2" username="USERNAME" password="PASSWORD" 
          maxActive="20" maxIdle="10" maxWait="-1"/>
</Context>

If you copy app1.xml to [tomcat]/conf/Catalina/localhost, you will deploy your application. If you remove app1.xml, you will perform undeploy. File name is context path, which means, that these two applications run on this URLs:

WARNING: The WAR file CANNOT BE IN WEBAPPS DIRECTORY!!! It has to be anywhere else. Tomcat will unzip the WAR file contents to webapps directory.





© Jiri Pinkas | this project on GitHub | related: JavaVids | Maven Central Repository Search | Java školení

Top Java Blogs is a Java blog aggregator (with English-written blogs only) focused on Java SE, Java EE, Spring Framework and Hibernate.

Made better & faster using https://www.yourkit.com/ Java Profiler