JNDI 之web项目数据源配置
1.把数据源配置到Server下context.xml 文件中(也可以配置在web.xml中)
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<Resource
name="jdbc/mysql"
scope="Shareable"
type="javax.sql.DataSource"
factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
url="jdbc:mysql://localhost:3306/test"
driverClassName ="com.mysql.jdbc.Driver"
username="root"
password="123456"
/>
</Context>
这样Spring等框架可以引用了. 下面做了一个简单的测试,在该web项目中获取数据库里的数据.
package com.iris.coon;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class Jndi {
public static void testConnection() {
String message = "Not Connected";
Connection conn=null;
ResultSet rst = null;
Statement stmt = null;
Context ctx;
try {
ctx = new InitialContext();
Context envContext = (Context) ctx.lookup("java:comp/env");
Object datasourceRef=envContext.lookup("jdbc/mysql");
DataSource ds=(DataSource)datasourceRef;
conn=ds.getConnection();
if (conn != null) {
message = "Got Connection " + conn.toString() + ", ";
stmt = conn.createStatement();
rst = stmt.executeQuery("select t.prp_code,t.prp_no from proposal t");
while(rst.next()){
int prp_code = rst.getShort("prp_code");
String prp_no = rst.getString("prp_no");
System.out.println(prp_code+" "+prp_no+"\t");
}
System.out.println("Jndi Test Succeed!");
}
} catch (NamingException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
新建index.jsp文件,调取testConnection方法得到结果.表示数据源配置是正确的.
对于这样的配置,spring的jee:jndi-lookup 直接就获取到.
<jee:jndi-lookup id="dataSource" jndi-name="jdbc/mysql"></jee:jndi-lookup>