我无法在tomcat中使用JNDI来连接MySQL

时间:2016-04-29 04:35:04

标签: java mysql eclipse tomcat jndi

我做了一切: how to connect tomcat 7 and mysql
但它仍然没有工作.....为什么?我错过了什么?

环境

操作系统:Win7
Eclipse:J2EE Mars
Tomcat:tomcat 8.0
java:1.8.0_73
db name:test
用户名:root
密码:123

控制器:

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(在我的项目中)

<!-- 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中

(在TOMCAT_HOME / conf中)
(也在localhost-config中的workspace \ Servers \ Tomcat v8.0服务器中)

<?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>

日志

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 ............

1 个答案:

答案 0 :(得分:1)

您已导入(并且可能被编程为)错误的DataSource。您的例外情况(java.lang.ClassCastException ... cannot be cast to javax.activation.DataSource)告诉您已使用javax.activation.DataSource,但您想要javax.sql.DataSource。修改com.joe.db.writeDB并更改

import javax.activation.DataSource;

import javax.sql.DataSource;

此外,您不需要 Class.forName("com.mysql.jdbc.Driver");(它不会伤害任何东西,但JDBC驱动程序现在会自行注册)。