在META-INF文件下配置context.xml文件 如下:
<?xml version='1.0' encoding='utf-8'?>
<Context docBase="ces" path="/ces">
<Resource name="jdbc/cesDB" type="javax.sql.DataSource" auth="Container"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:orcl"
username="ces"
password="ces"
maxWait="5000"
maxActive="10"
maxIdle="2"/>
</Context>
然后通过读配置文件的方式初始化 ,来获取连接对象::
package org.web.conn;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.NamingException;
public class DBconnecion {
public static Connection getDBConnection(){
Connection connection=null;
DataSource ds=null;
try{
//Retrieve the DataSource from JNDI
Context ctx=new InitialContext();
ds=(DataSource)ctx.lookup("java:comp/env/jdbc/emDB");
if(ds==null){
throw new RuntimeException("DataSource could not be found.");
}
//Get a database connection
connection=ds.getConnection();
}catch(SQLException e){
System.out.println(e);
}catch(NamingException e){
System.out.println(e);
}
return connection;
}
public static void close(ResultSet rs, PreparedStatement pstmt, Statement stmt, Connection conn){
if(rs !=null){
try{
rs.close();
}catch(SQLException se){
se.printStackTrace(System.err);
}
}
if(pstmt != null){
try{
pstmt.close();
}catch(SQLException se){
se.printStackTrace(System.err);
}
}
if(stmt != null){
try{
stmt.close();
}catch(SQLException se){
se.printStackTrace(System.err);
}
}
if(conn !=null){
try{
if(!conn.isClosed())
conn.close();
}catch(SQLException e){
e.printStackTrace(System.err);
}
}
}
public static void close(CallableStatement cstmt){
if(cstmt != null){
try{
cstmt.close();
}catch(SQLException se){
se.printStackTrace(System.err);
}
}
}
}
其他的文件可以可以通过引用该类的静态 方法来操作数据库