r3n0j
r3n0j

Reputation: 71

How to define default context elements with Tomcat?

We deploy an application on tomcat 9 (apache-tomcat-9.0.22).

The official documentation (https://tomcat.apache.org/tomcat-9.0-doc/config/context.html) says it's possible to define default context elements but it's not working for us.

We need to define a datasource and a mail server. If we define this resources in conf/server.xml file in GlobalNamingResources it works.

<GlobalNamingResources>
    <Resource name="mail" type="javax.mail.Session"... />
    <Resource name="jdbc/mydb" type="javax.sql.DataSource" driverClassName="oracle.jdbc.OracleDriver"... />
</GlobalNamingResources>

But in production, we cannot modify server.xml file. So we need to define this resources in an other file.

If we define resources in $CATALINA_BASE/conf/[enginename]/[hostname]/ROOT.xml file with a war named ROOT.war, it works :

<?xml version="1.0" encoding="UTF-8"?>
<!-- Context configuration file for my web application -->
<Context>
    <Resource name="mail" type="javax.mail.Session"... />
    <Resource name="jdbc/mydb" type="javax.sql.DataSource" driverClassName="oracle.jdbc.OracleDriver"... />
</Context>

This solution could be satisfactory but our war file must have a different name than ROOT.war (like MyApp_v42.war) and it will change with every update. We cannot rename the xml file every time we update.

If we define resources in the $CATALINA_BASE/conf/context.xml file or in $CATALINA_BASE/conf/[enginename]/[hostname]/context.xml.default file like documentation says we obtain a javax.naming.NameNotFoundException.

Thanks in advance!

Upvotes: 1

Views: 2235

Answers (1)

r3n0j
r3n0j

Reputation: 71

One solution is :

  • Define resources in conf/context.xml :
<?xml version="1.0" encoding="UTF-8"?>
<Context>
    <Resource name="mail" type="javax.mail.Session"... />
    <Resource name="jdbc/mydb" type="javax.sql.DataSource"... />
                               -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
    <WatchedResource>WEB-INF/tomcat-web.xml</WatchedResource>
    <WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>

    <Manager pathname="" />
</Context>
  • Use a deployment outside of the webapps directory, for example in wars/

  • Create an XML file ROOT.xml under the conf/Catalina/localhost/ that define the docBase attribute with a path relative to the webapps directory :

<?xml version="1.0" encoding="UTF-8"?>
<Context docBase="../wars/MyApp.war"></Context>

In this way :

  • the conf/server.xml file is not modify
  • the name of the war file is not necessary ROOT.xml
  • resources are defined in conf/context.xml

But :

  • you must have one file in conf/Catalina/localhost/ per .war
  • wars are not auto-deployed
  • if you change the name of the root war file, you must modify the docBase attribute in conf/Catalina/localhost/ROOT.xml file.

Upvotes: 1

Related Questions