Pre-Condition
Setup Tomcat Management User
To use the Tomcat Management tools, you must create a user with “admin” and “manager” roles. To do this, follow these steps:
- Open the
tomcat-users.xmlfile in theCATALINA_home/confdirectory with a text editor. - In this file, add the following entries to create the “admin” and “manager” roles:
<role rolename="manager"/>
<role rolename="admin"/>
- In addition, add the following entry to create the “admin” user:
<user username="admin" password="admin" fullName="Administrator" roles="admin,manager"/>
- Save and close the file
Add JDBC driver support to Tomcat
- Download the latest JDBC Driver from Oracle (e.g. here)
- Copy jar to
$CATALINA_HOME/common/lib
- Add a
context.xmlfile to the Application’s META-INF directory:
<?xml version="1.0" encoding="UTF-8"?>
<Context>
...
<Resource
name="jdbc/myoracle"
auth="Container"
type="javax.sql.DataSource"
factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
driverClassName="oracle.jdbc.OracleDriver"
username="<<myUsername>>"
password="<<myPassword>>"
url="jdbc:oracle:thin:@<<myOrcacleServer>>:<<myOrcaclePort>>:<<myOracleService>>"
maxWait="-1"
maxActive="20"
maxIdle="10"
validationQuery="SELECT 1+1 from dual"/>
...
</Context>
- Add the resource-ref tag to the Application’s
WEB-INFdirectory (not mandatory):
…
<resource-ref>
<description>Oracle Datasource</description>
<res-ref-name>jdbc/myoracle</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
- Add JDBC-Example code to Servlet-Example:
Context initContext;
try {
initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/myoracle");
Connection conn = ds.getConnection(); DatabaseMetaData meta = conn.getMetaData();
response.getWriter().write("<html><body>");
response.getWriter().write("Driver Name : "+meta.getDriverName()+"<br/>");
response.getWriter().write("Driver Version : "+meta.getDriverVersion()+"<br/>");
Statement statement = conn.createStatement();
String query = "select * from LOGIN_USER";
//
ResultSet resultSet = statement.executeQuery(query);
//
while (resultSet.next()) {
response.getWriter().write(resultSet.getString(2)+"<br/>");
}
// close connection
conn.close();
conn = null;
- See also: Tomcat JNDI Datasource Examples