您的位置:首页 > 其它

JNDI 之web项目数据源配置

2017-02-23 22:21 477 查看
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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  server jndi 数据源