开发环境:jdk1.6+myeclipse6.5+mysql5.0+tomcat6.0.14
1.第一步:在apache-tomcat-6.0.14/conf/context.xml中添加:用于配置JNDI的名字
其中的代码如下:
<Resource name="jdbc/mysql"
type="javax.sql.DataSource"
password="alen"
driverClassName="com.mysql.jdbc.Driver"
maxIdle="40"
maxWait="5000"
username="root"
url="jdbc:mysql://localhost:3306/spacedebris"
maxActive="40"/>
加到<Context> </Context>之间
2.第二步:在项目的web.xml加入代码:
<resource-ref>
<description>mysqlDB</description>
<res-ref-name>jdbc/mysql</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
放在<web-app version="2.4" > </web-app>之间
3.用jsp代码测试:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page import="java.sql.*,javax.sql.*,javax.naming.*"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'MySqlDSTest.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%
DataSource ds=null;
try{
InitialContext ctx=new InitialContext();
ds=(DataSource)ctx.lookup("java:comp/env/jdbc/mysql");
Connection conn=ds.getConnection();
conn.close();
out.println("JNDI连接MYSQL测试成功!");
}catch(Exception ex){
out.println(ex.getMessage());
}
%>
</body>
</html>
最后效果如下:
JNDI连接MYSQL测试成功!