`
soft901
  • 浏览: 36370 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

配置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 "
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics