2

I run a Tomcat 7 web application on 2 locations; in one location there is a MySQL database, in the other a SQL-Server. In the context.xml file of the webapp I defined two <Resources> that contain the database connection information for both databases. Because I am still developing I sometimes run the application with the MySQL server (at home), and sometimes with the SQL-server (at work).

Until now I have been recompiling the code every time to either connect to MySQL or SQL-Server, by changing change the line

//connect to MySQL
DataSource ds = (DataSource) env.lookup( "jdbc/mysql" );

into

//connect to SQL-Server
DataSource ds = (DataSource) env.lookup( "jdbc/sqlserver" );

Is there a simple(r) way to let the web application know on which location I am, for example with a setting in a xml file, so that the webapp knows with which database it has to connect?

reus
  • 143
  • 4
  • 10

2 Answers2

1

In the context definition for your application define only one data source with always the same name. Change the datasource definition depending on the location you are.

magomi
  • 6,599
  • 5
  • 31
  • 38
1

Make the JNDI name an external configuration setting which you retrieve as a properties file value or as a VM argument, or maybe as an environment variable value.

E.g. as a properties file config.properties which you put in the classpath:

db.jndi.name=jdbc/mysql

which you get as follows:

Properties properties = new Properties();
properties.load(input);
String dbJndiName = properties.getProperty("db.jndi.name");

Or as a VM argument which you specify in server's startup script:

-Ddb.jndi.name=jdbc/mysql

which you get as follows:

String dbJndiName = System.getProperty("db.jndi.name");
Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555