配置tomcat jndi mysql

1.先在%TOMCAT_HOME%\conf\server.xml中配置resource:

<Resource
name="jdbc/mysql"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
password="123456"
maxIdle="2"
maxWait="5000"
username="root"
url="jdbc:mysql://localhost:3306/test"
maxActive="4"/>


2.创建一个java项目(需要自己建一些包,然后打包放入tomcat下)或者tomcat项目,以tomcat项目为例(testJNDI),在web-inf下建立一个web.xml文件然后加入以下代码:

<resource-ref>
<description>jdbc/mysql</description>
<res-ref-name>jdbc/mysql</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>


3.需要在%TOMCAT_HOME%\conf\server.xml中配置ResourceLink,用以link到这个resource:

<Context
docBase="D:/dev/workspace/common/testJNDI"
path="/testJNDI"
reloadable="true"
workDir="D:\dev\workspace\common\testJNDI\work">
<ResourceLink
global="jdbc/mysql"
name="jdbc/mysql"
type="javax.sql.DataSourcer"/>
</Context>

如果不配置ResourceLink会出现异常:
org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null' 


4.增加一个index.jsp用于测试连接情况:

<%@ page contentType="text/html; charset=gb2312"%>
<%@ page import="java.sql.*"%>
<%@ page import="javax.naming.*"%>
<%@ page import="javax.sql.*"%>
<%
Context ctx = null;
DataSource ds = null;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;

try {
ctx = new InitialContext();
if (ctx == null)
out.println("no context");
ds = (DataSource) ctx.lookup("java:comp/env/jdbc/mysql");
if (ds == null)
out.println("no datasource");
conn = ds.getConnection();
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
String strSql = "select * from test";
rs = stmt.executeQuery(strSql);
while (rs.next()) {
out.println(rs.getString(2));
}
} catch (Exception ex) {
ex.printStackTrace();
out.println(ex.toString());
} finally {
if (rs != null)
rs.close();
if (stmt != null)
stmt.close();
if (conn != null)
conn.close();
if (ctx != null)
ctx.close();
}
%>


5.将mysql的connet jar放入到%TOMCAT_HOME%\common\lib下面:本交测试是mysql-connector-java-5.0.5-bin.jar。

本次测试出现了异常:
javax.naming.NameNotFoundException: Name mysql is not bound in this Context 

是由于在配置Resource时候,Resource的name后多了一个空格。
name="jdbc/mysql "
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值