LoLisSuck
LoLisSuck

Reputation: 19

I can't use JNDI in tomcat to connect MySQL

I did everything in this : how to connect tomcat 7 and mysql
But it still isn't working..... why? What have I missed?

Enviroment

OS : Win7
Eclipse : J2EE Mars
Tomcat : tomcat 8.0
java : 1.8.0_73
db name : test
username: root
password: 123


controller:

writeDB testDB = new writeDB(tablename);

writeDB.java

....
Class.forName("com.mysql.jdbc.Driver"); 
try{
      Context initContext = new InitialContext();
      Context envContext = (Context)initContext.lookup("java:/comp/env");
      //-------error------- 
      dataSource = (DataSource) envContext.lookup("jdbc/test");
      //-------error-------
   }catch(NamingException ex)
   {
      throw new RuntimeException(ex);   
   }

web.xml (in my project)

<!-- MySQL JNDI -->
<resource-ref>
    <description>MySQL DB</description>
    <res-ref-name>jdbc/test</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>

context.xml

(in TOMCAT_HOME/conf)
(Also in workspace\Servers\Tomcat v8.0 Server at localhost-config)

<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/eatST">
<Resource 
    name="jdbc/test"
    auth="Container" 
    type="javax.sql.DataSource"
    maxActice="100" 
    maxIdle="30" 
    maxWait="10000" 
    username="root"
    password="123" 
    driverClassName="com.mysql.jdbc.Driver"
    url="jdbc:mysql://localhost:3306/test?
         useUnicode=true&amp;characterEncoding=UTF8"
    factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
 />
 </Context>

Logs

Servlet.service() for servlet [commentCtr] in context 
with path [/eatST]      threw exception
java.lang.ClassCastException: org.apache.tomcat.dbcp.dbcp2.BasicDataSource   
cannot be cast to javax.activation.DataSource
     at com.joe.db.writeDB.<init>(writeDB.java:58)
     at com.joe.servlet.CommentCtr.doPost(CommentCtr.java:38)
     at ............

Upvotes: 1

Views: 711

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201517

You've imported (and presumable programmed to) an incorrect DataSource. Your exception (java.lang.ClassCastException ... cannot be cast to javax.activation.DataSource) is telling you that you have usedjavax.activation.DataSource, but you wanted javax.sql.DataSource. Modify com.joe.db.writeDB and change

import javax.activation.DataSource;

to

import javax.sql.DataSource;

Also, you don't need Class.forName("com.mysql.jdbc.Driver"); (it doesn't hurt anything, but JDBC drivers register themselves now).

Upvotes: 1

Related Questions