Web项目配置数据源——JNDI

Tomcat-->conf-->在context.xml节点中添加配置



   
    WEB-INF/web.xml

   
   


   
   
auth="Container" 
                 type="javax.sql.DataSource" 
                 maxActive="100" 
                 maxIdle="30" 
                 maxWait="10000" 
                 username="scott" 
                 password="smq" 
                 driverClassName="oracle.jdbc.OracleDriver"  
                 url="jdbc:oracle:thin:@localhost:1521:XE" />



Web项目-->Web-Root-->在web.xml节点中添加配置


xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 
    index.jsp
 

 
  jdbc/source
  javax.sql.DataSource
  Container
 


web项目-->src-->com.niit.util-->DBUtil.Java

public class DBUtil {

private DBUtil(){}

//JNDI方式配置数据源
public synchronized static Connection getConnectionByJNDI(){
Connection con = null;
try {
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/source");
con = ds.getConnection();
} catch (NamingException e) {
System.out.println("连接错误!");
// e.printStackTrace();
}catch(SQLException e){
System.out.println("获取连接失败!");
// e.printStackTrace();
}
return con;
}


public static void closeResource(ResultSet rs,Statement stmt,Connection con){

try {
if(rs != null){
rs.close();
}
if(stmt != null){
stmt.close();
}
if(con != null){
con.close();
}
}catch (SQLException e) {
System.out.println("关闭资源失败!");
// e.printStackTrace();
}
}
}


注意事项:
1、在context.xml中的引用的资源名称必须和web.xml中保持一致;
2、web容器中要添加数据库的驱动jar,将tomecat目录中lib文件夹下的class12文件替换为ojdbc14;
3、java中访问数据源应在web容器开启后在jsp或servlet中进行访问,不能再main方法中直接调用。

JNDI配置数据源就是应用服务器通过WEB容器连接数据库,达到分布式的开发并集成服务器的目的,不像JDBC直接使用应用程序进行数据库连接。不开启任何WEB服务器,就无法启动JNDI。

你可能感兴趣的:(java,web)