在tomcat6.0中配置JNDI的DBCP连接

来源:互联网 发布:新疆网络为什么这么差 编辑:程序博客网 时间:2024/06/05 10:33

 

  这里用JDK1.6和tomcat6.0 SQLServer 2000做为例子来讲解

   首先配置JDK:(装JDK1.6)

   JAVA_HOME:C:/Program Files/Java/jdk1.6.0_03

   CLASSPATH:.;%JAVA_HOME%/lib;%JAVA_HOME%/lib/tools.jar

    Path:.;JAVA_HOME%/bin;%JAVA_HOME%/jre/bin 

 

    然后安装tomcat6.0

    第一部:在apache-tomcat-6.0.14/conf/context.xml中添加:用于配置JNDI的名字
 
   ************************************************

 <Resource name="jdbc/EmployeeDB" auth="Container"
            type="javax.sql.DataSource" username="sa" password="sa"
            driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver" url="jdbc:sqlserver://localhost:1433;DatabaseName=pubs"
            maxActive="8" maxIdle="4"/>

  ************************************************

 

 

  第二部:在你的工程的WEB.xml中添加
 
  ************************************************


  <resource-ref>
  <description>
    Resource reference to a factory for java.sql.Connection
    instances that may be used for talking to a particular
    database that is configured in the server.xml file.
  </description>
  <res-ref-name>
    jdbc/EmployeeDB
  </res-ref-name>
  <res-type>
    javax.sql.DataSource
  </res-type>
  <res-auth>
    Container
  </res-auth>
 </resource-ref>

  ***********************************************

 

第三部:将sqljdbc.jar包添加到apache-tomcat-6.0.14/lib的目录下!

 

测试代码:写一个JSP页面即可,然后启动tomcat服务,代码如下:

 

 

 

<%@page contentType="text/html; charset=GBK"%>
<%@page import="java.sql.*" %>
<%@page import="javax.naming.*" %>
<%@page import="javax.sql.DataSource" %>
<HTML>
<HEAD>
<TITLE>JNDI测试</TITLE>
</HEAD>
<BODY>
<%
 try {
  Context ctx = new InitialContext();
  DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/EmployeeDB");
  conn = ds.getConnection();
  Statement st = conn.createStatement();
  ResultSet rs = st.executeQuery("select * from sysobjects");
  while(rs.next()){
   out.println(rs.getString(1) + "<br>");
  }
 } catch (NamingException e) {
  e.printStackTrace();
 } catch (SQLException e) {
  e.printStackTrace();
 }
%>
</BODY>
</HTML>

 

原创粉丝点击