How to Configure JNDI DataSource in Tomcat 8 with Java Configuration: - java

How to Configure JNDI DataSource in Java Configuration File Instead of Following Code Snippet in "web.xml" Servlet Context:
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/DatabaseName</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>

Note: Don't Forget to Copy the "mysql-connector-java-5.1.36.jar" Into Tomcat's "lib" Subfolder in Main Installation Folder.
First: Add following Dependency in Your "pom.xml" File:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.36</version>
</dependency>
Second: Create META-INF Folder and "context.xml" File in "webapp" Root Folder Like the Following Picture:
Third: Add the Following Code Snippet in "context.xml" File:
<?xml version='1.0' encoding='utf-8'?>
<Context>
<Resource name="jdbc/DatabaseName" auth="Container" type="javax.sql.DataSource"
maxActive="50" maxIdle="30" maxWait="10000"
username="DatabaseUsername" password="DatabasePasssword"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/DatabaseName"/>
</Context>
Fourth: Create the Following Bean in Spring Context Configuration File:
#Bean
public DataSource dataSource() {
JndiDataSourceLookup dataSource = new JndiDataSourceLookup();
dataSource.setResourceRef(true);
return dataSource.getDataSource("jdbc/DatabaseName");
}
Note: "jdbc/DatabaseName" is "name" Attribute that We Added Already in "context.xml" File.

To complete SMGs answer: for xml-configured Spring, I use the following code (note the "webapp" profile, as for unit-tests you need to have a webserver-independent datasource)
<beans profile="webapp">
<!-- get dataSources from web-container -->
<bean name="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean" scope="singleton">
<property name="jndiName" value="java:comp/env/jdbc/DatabaseName" />
<property name="resourceRef" value="true" />
</bean>
</beans>

It can be done in 3 steps:
Step 1:
Add below entry in tomcat conf/server.xml under GlobalNamingResources tag.
<Resource auth="Container" driverClassName="DB_Drive_class-name" maxActive="100" maxIdle="30" maxWait="10000" name="jdbc/MyJNDI" password="&&&&&&&&&&&&&" type="javax.sql.DataSource" url="jdbc:db2://URL:PORT/DBNAME" username="&&&&&&&&&"/>
Step 2:
Add below entry in tomcat conf/context.xml under root context tag.
<ResourceLink name="jdbc/MyJNDI" global="jdbc/MyJNDI" type="javax.sql.DataSource"/>
Step 3:
Add DataSource ref in web.xml
<resource-ref>
<description>DB2 Datasource</description>
<res-ref-name>jdbc/MyJNDI</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
Note: This is a global Tomcat configuration and DataSource can be shared with different applications.

Related

porting web app to Tomcat: javax.naming.NameNotFoundException:

New user of Tomcat (8.5.9) on Linux CentOS 7 with Java SE 8. I must be making a simple mistake. This should be a textbook example how to configure a JDBC connection pool for tomcat.
I have this error:
javax.naming.NameNotFoundException: Name [jdbc/pool1] is not bound in this Context. Unable to find [jdbc]
Any idea what I could doing wrong? Tomcat states It is NOT recommended to place <Context> elements directly in the server.xml file. Thus, my setup:
$CATALINA_HOME/webapps/myapp/META-INF/context.xml is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jdbc/pool1"
auth="Container"
type="javax.sql.DataSource"
username="xx"
password="xx"
driverClassName="oracle.jdbc.OracleDriver"
url="xx"
maxTotal="256"
maxIdle="8"
initialSize="4"
removeAbandonedTimeout="7200"
removeAbandonedOnBorrow="true"/>
<Resource name="jdbc/pool2"
auth="Container"
type="javax.sql.DataSource"
username="xx"
password="xx"
driverClassName="oracle.jdbc.OracleDriver"
url="xx"
maxTotal="256"
maxIdle="8"
initialSize="4"
removeAbandonedTimeout="7200"
removeAbandonedOnBorrow="true"/>
<ResourceLink name="jdbc/pool1"
global="jdbc/pool1"
type="javax.sql.DataSource"/>
<ResourceLink name="jdbc/pool2"
global="jdbc/pool2"
type="javax.sql.DataSource"/>
</Context>
$CATALINA_HOME/webapps/myapp/WEB-INF/web.xml is as follows:
...
<resource-ref>
<description>xxx</description>
<res-ref-name>jdbc/pool1</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
<resource-ref>
<description>xxx</description>
<res-ref-name>jdbc/pool1</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
...
The code causing the exception:
Context context = new InitialContext();
DataSource ds = (DataSource)context.lookup("jdbc/pool1");
conn = ds.getConnection();
I have not modified $CATALINA_HOME/conf/server.xml at all. Did I configure something incorrectly, or am I missing setting another file up somewhere?
UPDATE 1
I tried adding the above ResourceLinks to the GlobalNamingResources tag in the $CATALINA_HOME/conf/server.xml file, then stopping/starting Tomcat, but I got the same error.
UPDATE 2
I then added the Resource tags from context.xml above also to the server.xml file (GlobalNamingResources tag), stopping/starting tomcat, and got same error.
UPDATE 3
I got everything working with Andreas' expert help (thanks!) by changing the way java calls the pool:
Context initCtx = new InitialContext();
Context context = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource) context.lookup("jdbc/pool1");
conn = ds.getConnection();
Also, the ResourceLinks should not be in server.xml (they simply generate a warning in tomcat log).
Your $CATALINA_BASE/conf/server.xml file should contain the full <Resource> element. Remember to also add the JDBC driver jar file to Tomcat's $CATALINA_BASE/lib folder, since it is Tomcat, not your webapp, that needs it when the <Resource> is defined in server.xml.
Next, the META-INF/context.xml is a template that is used the first time your webapp is deployed. It gets copied to $CATALINA_BASE/conf/Catalina/localhost/myapp.xml, and is likely not updated/refreshed if you change META-INF/context.xml.
The .../Catalina/localhost/myapp.xml file should contain the <ResourceLink> element, mapping the name used by the webapp to the name used in server.xml. Keeping those two names the same is easiest, but not required.
Tomcat works fine without the <resource-ref> elements in WEB-INF/web.xml, but it's better if they are there, for compatibility with other Servlet containers.
Note: $CATALINA_BASE is usually the same as $CATALINA_HOME, i.e. the folder where Tomcat is installed, unless you explicitly configure it otherwise.
So, $CATALINA_BASE/conf/server.xml:
<?xml version='1.0' encoding='utf-8'?>
<Server ...>
...
<GlobalNamingResources>
...
<Resource name="jdbc/pool1" auth="Container" type="javax.sql.DataSource" ... />
<Resource name="jdbc/pool2" auth="Container" type="javax.sql.DataSource" ... />
...
</GlobalNamingResources>
...
</Server>
and $CATALINA_BASE/conf/Catalina/localhost/myapp.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<ResourceLink name="jdbc/pool1" global="jdbc/pool1" type="javax.sql.DataSource"/>
<ResourceLink name="jdbc/pool2" global="jdbc/pool2" type="javax.sql.DataSource"/>
</Context>
and place ojdbcXXX.jar in $CATALINA_BASE/lib.

connecting to derby database with tomcat as the server

How do i connect to derby database (that comes with the netbeans) ? I am using Tomcat as the server. Earlier i used the following statements to connect to the derby database,but then i used glassfish as the server.
Context context = new InitialContext();
DataSource ds = (DataSource)context.lookup("java:comp/env/jdbc/PollDatasource");
Connection connection = ds.getConnection();
But now using Tomcat as the server i am unaware how to do this.
Note : Tomcat and Derby are pre installed with netbeans IDE that i am using currently
In Tomcat find conf/context.xml, then edit and write something like this:
<Resource name="jdbc/PollDatasource" auth="Container" type="javax.sql.DataSource"
driverClassName="com.YourDriver"
url="jdbc:derby://localhost:1527/nameOfTheDatabase;create=true"
username="username" password="password" maxActive="20"
maxIdle="10" maxWait="-1" />
Note 1: With the above URL the driver will be org.apache.derby.jdbc.ClientDriver
Note 2 : You can also add the above information in META-INF/context.xml of your project. This becomes application specific.If you add the information in tomcat's context.xml that becomes global.
Note 3: Download the jar from this website.Download db-derby-10.9.1.0-bin.zip.It contains many files, including derby.jar and derbyclient.jar (along with much documentation).derbyclient.jar contains our friend org.apache.derby.jdbc.ClientDriver.class. derby.jar contains org.apache.derby.jdbc.EmbeddedDriver. Keep the downloaded jar in lib folder of Tomcat.
and in your application web.xml "resource-ref":
<resource-ref>
<description>my connection</description>
<res-ref-name>jdbc/PollDatasource</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
You may want to look at these questions :
Isn't it necessary to mention the name of archive in the Resource tag?
When is the tag I added in context.xml gets read?
What are steps followed in the look-up? what is looked first web.xml or context.xml?
You need to:
1) Copy your derbyclient-*.jar to ${TOMCAT_HOME}/lib.
2) Edit your server.xml and add the following lines to the section GlobalNamingResources:
<Resource auth="Container"
driverClassName="org.apache.derby.jdbc.EmbeddedDriver"
maxActive="8" maxIdle="4"
name="jdbc/my-ds" type="javax.sql.DataSource"
url="jdbc:derby:mydb;create=true"
username="myuser" password="mypassword" />
3) In your context definition, add:
<Context docBase="myapp"
path="/myapp"
reloadable="true"
...>
<ResourceLink name="jdbc/my-ds"
global="jdbc/my-ds"
type="javax.sql.DataSource" />
</Context>
4) Restart Tomcat.
The example you have requires JNDI. See the relevant tomcat versions docs on setting that up.
Or use a connection string, here's a page from derby docs http://db.apache.org/derby/integrate/plugin_help/derby_app.html

How to use JNDI DataSource provided by Tomcat in Spring?

It is said that in the Spring javadoc article about DriverManagerDataSource class, that this class is very simple and that it is recommended
to use a JNDI DataSource provided by the container. Such a DataSource can be exposed as a DataSource bean in a Spring ApplicationContext via JndiObjectFactoryBean
The question is: how do I accomplish this?
For example, if I wish to have DataSource bean to access my custom MySQL database, what would I require then? What should I write in the context configuration, etc?
If using Spring's XML schema based configuration, setup in the Spring context like this:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jee="http://www.springframework.org/schema/jee" xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd">
...
<jee:jndi-lookup id="dbDataSource"
jndi-name="jdbc/DatabaseName"
expected-type="javax.sql.DataSource" />
Alternatively, setup using simple bean configuration like this:
<bean id="DatabaseName" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/DatabaseName"/>
</bean>
You can declare the JNDI resource in tomcat's server.xml using something like this:
<GlobalNamingResources>
<Resource name="jdbc/DatabaseName"
auth="Container"
type="javax.sql.DataSource"
username="dbUser"
password="dbPassword"
url="jdbc:postgresql://localhost/dbname"
driverClassName="org.postgresql.Driver"
initialSize="20"
maxWaitMillis="15000"
maxTotal="75"
maxIdle="20"
maxAge="7200000"
testOnBorrow="true"
validationQuery="select 1"
/>
</GlobalNamingResources>
And reference the JNDI resource from Tomcat's web context.xml like this:
<ResourceLink name="jdbc/DatabaseName"
global="jdbc/DatabaseName"
type="javax.sql.DataSource"/>
Reference documentation:
Tomcat 8 JNDI Datasource HOW-TO
Tomcat 8 Context Resource Links Reference
Spring 4 JEE JNDI Lookup XML Schema Reference
Spring 4 JndiObjectFactoryBean Javadoc
Edit: This answer has been updated for Tomcat 8 and Spring 4. There have been a few property name changes for Tomcat's default datasource resource pool setup.
With Spring's JavaConfig mechanism, you can do it like so:
#Configuration
public class MainConfig {
...
#Bean
DataSource dataSource() {
DataSource dataSource = null;
JndiTemplate jndi = new JndiTemplate();
try {
dataSource = jndi.lookup("java:comp/env/jdbc/yourname", DataSource.class);
} catch (NamingException e) {
logger.error("NamingException for java:comp/env/jdbc/yourname", e);
}
return dataSource;
}
}
Assuming you have a "sampleDS" datasource definition inside your tomcat configuration, you can add following lines to your applicationContext.xml to access the datasource using JNDI.
<jee:jndi-lookup expected-type="javax.sql.DataSource" id="springBeanIdForSampleDS" jndi-name="sampleDS"/>
You have to define the namespace and schema location for jee prefix using:
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd"
Documentation: C.2.3.1 <jee:jndi-lookup/> (simple)
Example:
<jee:jndi-lookup id="dataSource" jndi-name="jdbc/MyDataSource"/>
You just need to find out what JNDI name your appserver has bound the datasource to. This is entirely server-specific, consult the docs on your server to find out how.
Remember to declare the jee namespace at the top of your beans file, as described in C.2.3 The jee schema.
Another feature:
instead of of server.xml, you can add "Resource" tag in
your_application/META-INF/Context.xml
(according to tomcat docs)
like this:
<Context>
<Resource name="jdbc/DatabaseName" auth="Container" type="javax.sql.DataSource"
username="dbUsername" password="dbPasswd"
url="jdbc:postgresql://localhost/dbname"
driverClassName="org.postgresql.Driver"
initialSize="5" maxWait="5000"
maxActive="120" maxIdle="5"
validationQuery="select 1"
poolPreparedStatements="true"/>
</Context>
According to Apache Tomcat 7 JNDI Datasource HOW-TO page there must be a resource configuration in web.xml:
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/TestDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
That works for me
In your spring class, You can inject a bean annotated like as
#Autowired
#Qualifier("dbDataSource")
private DataSource dataSource;
and You add this in your context.xml
<beans:bean id="dbDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<beans:property name="jndiName" value="java:comp/env/jdbc/MyLocalDB"/>
</beans:bean>
You can declare the JNDI resource in tomcat's server.xml using
<Resource name="jdbc/TestDB"
global="jdbc/TestDB"
auth="Container"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/TestDB"
username="pankaj"
password="pankaj123"
maxActive="100"
maxIdle="20"
minIdle="5"
maxWait="10000"/>
back to context.xml de spring add this
<ResourceLink name="jdbc/MyLocalDB"
global="jdbc/TestDB"
auth="Container"
type="javax.sql.DataSource" />
if, like this exmple you are injecting connection to database, make sure that MySQL jar is present in the tomcat lib directory, otherwise tomcat will not be able to create the MySQL database connection pool.
I found this solution very helpful in a clean way to remove xml configuration entirely.
Please check this db configuration using JNDI and spring framework.
http://www.unotions.com/design/how-to-create-oracleothersql-db-configuration-using-spring-and-maven/
By this article, it explain how easy to create a db confguration based on database jndi(db/test) configuration. once you are done with configuration then all the db repositories are loaded using this jndi. I did find useful. If #Pierre has issue with this then let me know. It's complete solution to write db configuration.

How can I use Java console app and Hibernate using Tomcat Context?

I have some Java-console-apps. which are using Hibernate to take care some database stuff (I use MySQL). Now, I want Hibernate to use datasource from Tomcat Context. Could anyone tell me how?
Tomcat wiki contains the needed configuration.
in context.xml:
<?xml version="1.0" encoding="UTF-8"?> <Context antiJARLocking="true" path="/DVDStore">
<Resource auth="Container"
driverClassName="com.mysql.jdbc.Driver" maxActive="30" maxIdle="10" maxWait="10000" name="jdbc/sakila" password="*****"
type="javax.sql.DataSource" url="jdbc:mysql://localhost/sakila" username="*****"/>
</Context>
In WEB-INF/web.xml .
<resource-ref>
<description>This is a MySQL database connection</description>
<res-ref-name>jdbc/sakila</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
In hibernate.cfg.xml:
<!-- using container-managed JNDI -->
<propertyname="hibernate.connection.datasource">
java:comp/env/jdbc/sakila
</property>
You can find more in The TomcatHibernate Wiki
Edit:
In case you want to access the context directly, this is the way to do it problematically
ServletContext sc = getServletContext();
String parameterValue = sc.getInitParameter("parameterName");

Tomcat6 MySql JDBC Datasource configuration

I've always used Spring's dependency injection to get datasource objects and use them in my DAOs, but now, I have to write an app without that.
With Spring I can write something like this:
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://127.0.0.1/app?characterEncoding=UTF-8" />
<property name="username" value="u" />
<property name="password" value="p" />
</bean>
But how can I use datasource in my DAOs without Spring or anything? I'm using servlets and JSPs only. Performance is very important factor.
Believe it or not, people were writing applications before Spring and some are still not using it :) In your case, you could use Tomcat connection pool (and there is a complete configuration example for MySQL in the documentation). Let me summarize it:
First, put your driver in $CATALINA_HOME/lib.
Then, configure a JNDI DataSource in Tomcat by adding a declaration for your resource to your Context:
<Context path="/DBTest" docBase="DBTest"
debug="5" reloadable="true" crossContext="true">
<!-- maxActive: Maximum number of dB connections in pool. Make sure you
configure your mysqld max_connections large enough to handle
all of your db connections. Set to -1 for no limit.
-->
<!-- maxIdle: Maximum number of idle dB connections to retain in pool.
Set to -1 for no limit. See also the DBCP documentation on this
and the minEvictableIdleTimeMillis configuration parameter.
-->
<!-- maxWait: Maximum time to wait for a dB connection to become available
in ms, in this example 10 seconds. An Exception is thrown if
this timeout is exceeded. Set to -1 to wait indefinitely.
-->
<!-- username and password: MySQL dB username and password for dB connections -->
<!-- driverClassName: Class name for the old mm.mysql JDBC driver is
org.gjt.mm.mysql.Driver - we recommend using Connector/J though.
Class name for the official MySQL Connector/J driver is com.mysql.jdbc.Driver.
-->
<!-- url: The JDBC connection url for connecting to your MySQL dB.
-->
<Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="javauser" password="javadude" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/javatest"/>
</Context>
Declare this resource in your web.xml:
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<description>MySQL Test App</description>
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/TestDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
And get the datasource with a JNDI lookup in your application:
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource) envCtx.lookup("jdbc/TestDB");
Connection conn = ds.getConnection();
... use this connection to access the database ...
conn.close();
Note that such lookup is usually coded in a ServiceLocator (when you can't have a a DI container or a framework inject it for you).
I used to get error with sybase, I had missing META-INF folder in WebContent folder. Putting context.xml in that fixed the error Cannot create JDBC driver of class '' for connect URL 'null'...
// www.abbulkmailer.com
My context.xml looks like
<Context path="/reports" docBase="reports" debug="5" reloadable="true" crossContext="true">
<Resource name='jdbc/ASCSybaseConnection'
auth='Container'
type='javax.sql.DataSource'
username='fdd'
password='555'
driverClassName='com.sybase.jdbc2.jdbc.SybDriver'
maxActive='100'
maxIdle='100'
minIdle='10'
removeAbandoned="true"
removeAbandonedTimeout="60"
testOnBorrow="true"
logAbandoned="true"
url='jdbc:sybase:Tds:1.3.4.5:654/DB'/>
</Context>
You can declare your data source as a JNDI object and retrieve a datasource via a JNDI lookup:
DataSource ds = (DataSource)
envCtx.lookup("jdbc/EmployeeDB");
as documented here and here.
That's as bare-bones as you can get, so from there on, performance is completely up to you.

Categories

Resources