JNDI数据源

1,在META-INF下新建context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context>
	<Resource name="jdbc/testVideo"      
       auth="Container"      
       type="javax.sql.DataSource"      
       driverClassName="com.mysql.jdbc.Driver"      
       url="jdbc:mysql://localhost/testVideo"      
       username="root"      
       password="123456"      
       maxActive="50"      
       maxIdle="20"      
       maxWait="10000" />  
</Context>

2,在web.xml中加入配置
<resource-ref> 
                <res-ref-name> jdbc/testVideo </res-ref-name> 
                <res-type> javax.sql.DataSource </res-type> 
                <res-auth> Container </res-auth> 
        </resource-ref> 

3,最后是调用的class

import java.sql.*;
import javax.sql.*;
import javax.naming.*;

public class DBConnection {
	public Connection getConnection() throws SQLException, NamingException {
		// 初始化查找命名空间
		Context initContext = new InitialContext();

		Context envContext = (Context) initContext.lookup("java:/comp/env");
		// 找到DataSource

		DataSource ds = (DataSource) envContext.lookup("jdbc/testVideo");
		return ds.getConnection();
	}}

猜你喜欢

转载自geek41.iteye.com/blog/1165720