META-INF文件下新建context.xml,里面的内容为:
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/">
<Resource
name="jdbc/bbs"
scope="Shareable"
type="javax.sql.DataSource"
<!-- 不是org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory,这是JDK1.7及以下版本中的写法
JDK1.8中没有这个包,而是用org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory -->
factory="org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory"
url="jdbc:mysql://localhost:3306/bbs"
driverClassName ="com.mysql.jdbc.Driver"
username="root"
password="123456"
/>
</Context>
数据库连接池专用类JndiBean.java:
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import util.DBPoolException;
/**
* 从系统配置的JNDI数据连接池中获得数据库连接
*
* @author john
*
*/
public class JndiBean {
/**
* 从系统配置的JNDI数据连接池中获得数据库连接
*
* @return 获得的数据库连接,该连接在使用之后应该释放(close)
* @throws NamingException
* @throws SQLException
* @throws Exception
*/
public static Connection getConnection() throws DBPoolException, NamingException, SQLException {
Connection conn = null;
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource) envCtx.lookup("jdbc/bbs");
if (ds != null) {
conn = ds.getConnection();
} else
throw new DBPoolException("Can't find JNDI data source!");
if (conn == null)
throw new DBPoolException("Can't establish connection!");
return conn;
}
public static void main(String args[]) throws DBPoolException, NamingException, SQLException{
Connection conn=JndiBean.getConnection();
System.out.println("OK");
}
}
实际连接中的使用:
public static boolean isUserExisted(String userName){
boolean result=false;
Connection conn=null;
try{
Context c = new InitialContext();
DataSource ds = (DataSource)c.lookup("java:comp/env/jdbc/bbs");
conn = ds.getConnection();
/*此处与一般数据库连接的处理相同,写上所需处理的sql语句、参数、结果的处理,以下为示例
String sql="select count(*) from user where username=?";
PreparedStatement ps=conn.prepareStatement(sql);
ps.setString(1, userName);
ResultSet rs=ps.executeQuery();
rs.next();
if(rs.getInt(1)>0)result=true;*/
}catch(Exception e){
e.printStackTrace();
}
finally{
try {
if(conn!=null&&!conn.isClosed()){
conn.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
需要注意的是不同版本的JDK所需要的DBCP的包是不同的,可以到官网:
http://commons.apache.org/proper/commons-dbcp/去查看。