What is a Tomcat Datasource?
One of the facilities Tomcat provides is to maintain JDBC datasources.
Instead of each application maintaining a datasource and connection pools to the datasource, it is possible to pass that responsibility to Tomcat.
Once Tomcat is configured with a Datasource, applications can simply request the datasource from Tomcat whenever they need it. The configuration details about the datasource are not known by the application. All the applications know is the JNDI name of the datasource.
Let us configure Tomcat to create a datasource to the confuciusDB.
Open the file context.xml in your <tomcat_install_dir>/config and update it, like this:
<?xml version='1.0' encoding='utf-8'?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- The contents of this file will be loaded for each web application -->
<Context>
<!-- Default set of monitored resources -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<!-- Uncomment this to disable session persistence across Tomcat restarts -->
<!--
<Manager pathname="" />
-->
<!-- Uncomment this to enable Comet connection tacking (provides events
on session expiration as well as webapp lifecycle) -->
<!--
<Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
-->
<Resource name="jdbc/confuciusDB" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="confucius" password="changeit" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/confuciusDB"/>
</Context>
We have created a datasource with the name "jdbc/confuciusDB" providing it with the database URL, username, password and specifications for the connection pool.Now we can use JNDI to get this datasource from inside our code.
Update your HelloWorld.java, like this:
package org.confucius;
import java.io.IOException;
import java.sql.Connection;
import java.sql.Statement;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
public class HelloWorld extends HttpServlet{
public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
try {
// Use JNDI to get the datasource from tomcat
InitialContext cxt = new InitialContext();
DataSource ds = (DataSource) cxt.lookup( "java:/comp/env/jdbc/confuciusDB" );
response.getWriter().println("DataSource = " + ds);
// Now we can use the datasource (this code block has nothing to do with JNDI)
Connection conn = ds.getConnection();
Statement stmt = conn.createStatement();
stmt.execute("create table fruits (name VARCHAR(32), quantity INT)");
stmt.close();
conn.close();
}
catch (Exception e){
e.printStackTrace(response.getWriter());
}
}
}
We first open a JNDI context, then use the lookup() method.
Note that we have used the full tomcat JNDI name of the datasource.
The exact name of the resource is decided by the service provider, in this case, tomcat.
Once we have the datasource, we can open connections and run SQL queries.
JNDI has helped us get the datasource from Tomcat. Tomorrow, if Tomcat changes its datasource management implementation, our code will still work without any changes (provided Tomcat does not change the datasource name).
Update your web.xml to map the HelloWorld servlet, like this:
<web-app>
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>org.confucius.HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
Build and deploy HelloWorld.war, then point your browser to:
http://localhost:8080/HelloWorld/hello
You will see the datasource printed to the browser.
If you open your mysql command line client, you can see the tabel 'fruits' created:
mysql> show tables;
+-----------------------+
| Tables_in_confuciusdb |
+-----------------------+
| cart |
| fruits |
| user |
+-----------------------+
3 rows in set (0.00 sec)
No comments:
Post a Comment