原文作者:阿堂
在j2ee项目中,使用数据源配置,无外乎jdbc和jndi的配置,对于jdbc配置,没有什么好说的,对于jndi的配置,要稍显麻烦一些.这里分三种情况总结一下:第一种是没有用任何框架,第二种是只使用struts框架,第三种是使用struts和hibernate框架整合(ssh时类 似).
(以下是指的tomcat5.5环境,在tomcat5.0环境中,在server.xml中的写法,有点不一样,具体请参看阿堂写的在"Tomcat中 配置数据源出现问题的解决方法" http://blog.sina.com.cn/s/blog_4c925dca010098u5.html )
第一种情况没有使用任何框架
第一步.在web.xml中配置如下
<description>MYSQL JNDI TEST</description> <resource-ref> <description>DB Connection test</description> <res-ref-name>jdbc/test</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref>
第二步 在tomcat的server.xml文件中配置如下
放在<host></host>之间就可以了
<Context path="/jdniTest080220" debug="0" reloadable="true" privileged="true" docBase="E:\workprojects\jndiTest080220" workDir="E:\workprojects\jndiTest080220\WebRoot"> <Resource name="jdbc/test" auth="Container" type="javax.sql.DataSource" driverClassName="org.gjt.mm.mysql.Driver" url="jdbc:mysql://localhost:3306/test" username="root" password="admin" maxActive="20" maxIdle="10" maxWait="10000" /> </Context>
第三步.在jsp文件具体调用
<% DataSource ds = null; try{ Context initCtx = new InitialContext(); if (initCtx == null) throw new Exception("Initial Failed!"); Context ctx = (Context) initCtx.lookup("java:comp/env"); if (ctx != null) ds = (DataSource) ctx.lookup("jdbc/test"); if (ds == null) throw new Exception("Look up DataSource Failed!"); }catch (Exception e){ System.out.println(e.getMessage()); } %> <% Connection conn = ds.getConnection(); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("select * from student"); while (rs.next()){ %> <%=rs.getInt(1) %>:<%=rs.getString(2) %> <% } rs.close(); stmt.close(); conn.close(); %>
在ie中调用方法 http://localhost:8888/jdniTest080220/
第二种情况只使用struts框架
第一步.在tomcat中的server.xml文件中<GlobalNamingResources></GlobalNamingResources>之间添加如下代码
<Resource name="jdbc/sqlserver" auth="Container" type="javax.sql.DataSource" driverClassName="com.microsoft.jdbc.sqlserver.SQLServerDriver" url="jdbc:microsoft:sqlserver://localhost:1433;databaseName=Logis;SelectMethod=Cursor" username="sa" password="" maxActive="50" maxIdle="4" maxWait="5000"/>
第二步在tomcat对应的如下目录中%tomcat5520%\Catalina\localhost新建一个TmsOrder.xml文件,内容如下
<?xml version='1.0' encoding='utf-8'?> <Context docBase="TmsOrder" path="/TmsOrder" workDir="work\Catalina\localhost\TmsOrder"> <ResourceLink global="jdbc/sqlserver" name="jdbc/sqlserver" type="javax.sql.DataSourcer"/> </Context>
第三步在项目中一个公共类中,调用jndi数据源的方法如下
public class GetConnection {
private Connection conn = null;
private DataSource dataSource = null;
private Context ctx = null;
public GetConnection(){}
public Connection getConnection() {
try{
ctx = new InitialContext();
dataSource =(DataSource)ctx.lookup("java:comp/env/jdbc/sqlserver");
conn = dataSource.getConnection();
return conn;
}catch(Exception e){
System.out.println("获得连接池:"+e.getMessage());
return conn;
}
}
public void closeConn() {
try {
if( conn != null ){
conn.close();
}
} catch( SQLException e ) {
e.printStackTrace();
}
}
}
在ie中调用 http://localhost:8888/TmsOrder
第三种情况使用struts+hibernate框架(使用ssh时,做法类似)
第一步在hibernate.cfg.xml文件配置如下
<hibernate-configuration> <session-factory> <property name="show_sql">true</property> <property name="connection.datasource"> java:comp/env/jdbc/mldn </property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <mapping resource="cn/mldn/lxh/login6/vo/Person.hbm.xml" /> </session-factory> </hibernate-configuration>
第二步.在tomcat中的server.xml文件中<GlobalNamingResources></GlobalNamingResources>之间添加如下代码
<Resource name="jdbc/mldn" auth="Container" type="javax.sql.DataSource" driverClassName="org.gjt.mm.mysql.Driver" url="jdbc:mysql://localhost:3306/mldn" username="root" password="admin" maxActive="50" maxIdle="4" maxWait="5000"/>
第三步在tomcat对应的如下目录中%tomcat5520%\Catalina\localhost新建一个SHLogin.xml文件,内容如下
<?xml version='1.0' encoding='utf-8'?> <Context docBase="TmsOrder" path="/TmsOrder" workDir="work\Catalina\localhost\TmsOrder"> <ResourceLink global="jdbc/sqlserver" name="jdbc/sqlserver" type="javax.sql.DataSourcer"/> </Context>
第四步.在公共类中调用连接数据源的方法如下
public class DefaultSessionFactory {
public static Session getSession() {
Session session = null;
session = new Configuration().configure().buildSessionFactory().openSession();
return session;
}
}
在ie中调用 http://localhost:8888/SHLogin
在tomcat 6.0下配置JNDI及在Spring中的使用
第一步:在tomcat6.0的conf文件夹下找到 context.xml 文件,在<context></context>中加入<Resource name="jdbc/demo" <!-- JNDI名称 --> auth="Container" <!-- 此处和web.xml中对应 --> type="javax.sql.DataSource" <!-- 数据源类型 --> password="1234" <!-- 数据库访问密码 --> username="demo" <!-- 数据库访问用户名 --> driverClassName="oracle.jdbc.OracleDriver" <!-- 数据库驱动类 --> url="jdbc:oracle:thin:@127.0.0.1:1521:DEMO" <!-- 数据库访问url --> maxActive="100" <!-- 最大活动数 --> maxIdle="30" maxWait="5000" <!-- 最大等待时间 --> />
第二步:在web.xml中加入
<resource-ref> <res-ref-name>jdbc/demo</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref>
第三步:在spring配置文件中配置dataSource
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="java:comp/env/jdbc/smap"></property> </bean>
如此3步,在Spring中即可进行数据源注入。
JNDI使用小指南
1、配置Tomcat5.5.X的Server.xml,在<host>下面加上<Context path="/JNDIDemo" docBase="D:\workspace\JNDIDemo\WebRoot" debug="0" reloadable="true" crossContext="true"> <Logger className="org.apache.catalina.logger.FileLogger" prefix="localhost_quality_log." suffix=".txt" timestamp="true"/> <Resource name="jdbc/test" <!-- JNDI数据池名称 --> type="javax.sql.DataSource" <!-- 数据类 --> password="karid" <!-- 密码 --> driverClassName="oracle.jdbc.driver.OracleDriver" <!-- 驱动 --> maxIdle="2" <!-- 最少可用lia --> maxWait="5000" <!-- 最大等待时间 5秒 --> username="karid" <!-- 用户名 --> url="jdbc:oracle:thin:@127.0.0.1:1521:karid" maxActive="4" <!-- 最大可用连接 --> /> <ResourceParams name="jdbc/test"> <parameter> <name>removeAbandoned</name> <!-- Abandoned DB connections are removed and recycled --> <value>true</value> </parameter> <parameter> <name>removeAbandonedTimeout</name> <!-- Use the removeAbandonedTimeout parameter to set the number of seconds a DB connection has been idle before it is considered abandoned. --> <value>60</value> </parameter> <parameter> <name>logAbandoned</name> <!-- Log a stack trace of the code which abandoned --> <value>false</value> </parameter> <parameter> <name>factory</name> <!--DBCP Basic Datasource Factory --> <value>org.apache.commons.dbcp.BasicDataSourceFactory</value> </parameter> </ResourceParams>
2、配置web.xml
<description>MySQL Test App</description> <resource-ref> <description>DB Connection</description> <res-ref-name>jdbc/test</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref>
3、JNDI使用
Java代码
public class DataSourceFactory{
private static DataSource ds;
public static DataSource createDataSourde(){
if (ds == null) {
try {
Context initContext = new InitialContext();
if (initContext == null) System.out.println("无配置环境");
Context envContext = (Context) initContext.lookup("java:/compenv");
ds = (DataSource) envContext.lookup("jdbc/test"); //根据名称取得数据源
}catch (NamingException e){
e.printStackTrace();
}
}
return ds;
}
}