您的位置:首页 > 其它

Web项目配置数据源——JNDI 标签: web

2016-10-13 12:52 489 查看
Tomcat-->conf-->在context.xml节点中添加配置

<?xml version='1.0' encoding='utf-8'?>

<Context>

    <!-- Default set of monitored resources -->

    <WatchedResource>WEB-INF/web.xml</WatchedResource>

    <!-- Uncomment this to disable session persistence across Tomcat restarts -->

    <!--

    <Manager pathname="" />

    -->

    <!-- Uncomment this to enable Comet connection tacking (provides events

         on session expiration as well as webapp lifecycle) -->

    <!--

    <Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />

    -->
<Resource name="jdbc/source"
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" />

</Context>

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

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.5" 
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">
  <welcome-file-list>

    <welcome-file>index.jsp</welcome-file>

  </welcome-file-list>

  <resource-ref>

  <res-ref-name>jdbc/source</res-ref-name>

  <res-type>javax.sql.DataSource</res-type>

  <res-auth>Container</res-auth>

  </resource-ref>

</web-app>

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。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: