[英]I can't use JNDI in tomcat to connect MySQL
我做了这一切: 如何连接 tomcat 7 和 mysql
但它仍然不起作用......为什么? 我错过了什么?
操作系统:Win7
Eclipse : J2EE 火星
Tomcat : tomcat 8.0
爪哇:1.8.0_73
数据库名称:测试
用户名:root
密码:123
writeDB testDB = new writeDB(tablename);
....
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);
}
<!-- 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>
(在 TOMCAT_HOME/conf 中)
(也在 localhost-config 的 workspace\\Servers\\Tomcat v8.0 Server 中)
<?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&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 ............
您已导入(并且可能已编程)不正确的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 驱动程序现在注册自己)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.