The context.xml file is an optional file which contains a <Context> tag (Context Fragment) for a single Tomcat web application. This can be used to define certain behaviours for your application, JNDI resources and other settings.
The context.xml file was introduced in Tomcat 5, to remove Context settings from the server.xml file.
The Context Fragment can be embedded in server.xml, placed in the <CATALINA>/conf folder, or placed inside each application in the META-INF folder in a file called context.xml. The META-INF method is preferred as this means changes to the context don't require Tomcat to be restarted. You can restart your application by modifying web.xml when automatic reloading is active, or reloading manually with the Tomcat Manager.
Your context.xml file should be installed in the META-INF folder of your application, as META-INF/context.xml. The META-INF folder belongs at the same level as WEB-INF (not inside it).
index.jsp /WEB-INF web.xml /lib myjar.jar /classes myclass.class /META-INF context.xml
Surprisingly, not many developers use this file within their applications yet, although it is very useful. Switching to the use of a context.xml file removes all dependencies from server.xml, making the application much more portable and easier to deploy.
This file provides a JNDI resource representing a MySQL datasource, and a security realm.
<?xml version="1.0" encoding="UTF-8"?> <Context> <!-- Specify a JDBC datasource --> <Resource name="jdbc/mydatabase" auth="Container" type="javax.sql.DataSource" username="YOUR_USERNAME" password="YOUR_PASSWORD" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://mysql.metawerx.net:3306/YOUR_DATABASE_NAME?autoReconnect=true" validationQuery="select 1" maxActive="10" maxIdle="4"/> <!-- Specify the security realm and location of the users file <Realm className="org.apache.catalina.realm.MemoryRealm" pathname="/tomcat/webapps/ROOT/WEB-INF/users.xml" /> --> </Context>
// Get DataSource Context ctx = new InitialContext(); DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/mydatabase"); // Get Connection and Statement Connection c = ds.getConnection(); Statement s = c.createStatement();
Additional databases can be added by adding an extra <Resource> element to the context.xml file, with a different name (eg: jdbc/customerDatabase).