server.xml
context.xml
Java代码:
public class DBconn {
private static String datasoucename = "java:comp/env/jdbc/test";
Context context = null;
DataSource ds = null;
Connection conn = null;
public Connection getconn() {
return initConnection();
}
public DataSource getDataSource() {
try {
context = new InitialContext();
} catch (NamingException e) {
System.err.println("连接池上下文不存在! " + e.getMessage());
}
try {
ds = (DataSource) context.lookup(datasoucename);
} catch (NamingException e) {
System.err.println("数据源没发现! " + e.getMessage());
}
return ds;
}
private Connection initConnection() {
try {
context = new InitialContext();
} catch (NamingException e) {
System.err.println("连接池上下文不存在! " + e.getMessage());
}
try {
ds = (DataSource) context.lookup(datasoucename);
} catch (NamingException e) {
System.err.println("数据源没发现! " + e.getMessage());
}
try {
conn = ds.getConnection();
} catch (SQLException e) {
System.err.println("获取连接失败! " + e.getMessage());
}
return conn;
}
public void freeConnection() {
try {
conn.close();
} catch (Exception e) {
System.err.println("释放连接出错! ");
e.printStackTrace();
}
}
}