zoukankan      html  css  js  c++  java
  • tomcat+dbcp+jndi 配置

    1)添加jar包 tomcat6中 TOMCAT_HOME/lib 下是公用jar包

    dbcp需要3个jar包:Jakarta-Commons DBCP,Jakarta-Commons Collections,Jakarta-Commons Pool, 但是tomcat6已经用1个tomcat-dbcp.jar包含了这3个jar包,该包在 TOMCAT_HOME/lib 下,因此在tomcat下不需要再添加dbcp相关的3个包;

    将mysql-connector-java-5.1.6-bin.jar 拷贝到 TOMCAT_HOME/lib 下;

    2)添加数据源

    在 TOMCAT_HOME/conf/context.xml 中 添加数据源:

    <Context> 
       <WatchedResource>WEB-INF/web.xml</WatchedResource> 
        <Resource name="jdbc/test" auth="Container" type="javax.sql.DataSource" 
                       maxActive="100" maxIdle="30" maxWait="10000" 
                      username="root" password="" driverClassName="com.mysql.jdbc.Driver" 
                       url="jdbc:mysql://localhost:3306/test?autoReconnect=true"/> 
    </Context> 

    3)在web.xml 中引用数据源

    <display-name>JNDI Test</display-name>     
       <description>A test for using of JNDI</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>

      4)在jsp(或java)中使用数据源

    <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %> 
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 
       
    <sql:query var="rs" dataSource="jdbc/test"
    select * from test 
    </sql:query> 
       
    <html> 
      <head> 
        <title>DB Test</title> 
      </head> 
      <body> 
       
      <h2>Results</h2> 
         
    <c:forEach var="row" items="${rs.rows}"
        id ${row.id}<br/> 
        str ${row.str}<br/> 
    </c:forEach> 
       
      </body> 
    </html> 

      

     5)tomcat的jndi实用类

    /**
         * 从数据库连接池获取数据库的链接
         */
        public Connection getConnection() {
              try 
                  Context  context =  new InitialContext();
                   DataSource ds = (DataSource) context.lookup("java:comp/env/jdbc/oa"); 
                } catch (NamingException e) { 
                    e.printStackTrace(); 
                    throw new RuntimeException("jndi 数据源加载失败!"); 
               }
                 
            boolean succ = false;<br>                Connection conn=null;<br>      try {
                conn = ds.getConnection();
                succ = true;
            catch (SQLException e) {
                e.printStackTrace();
                System.out.println("connection error");
            }
            return conn;
        }
  • 相关阅读:
    archlinux .bash_history
    Ubuntu环境下挂载新硬盘
    软碟通 UltraISO U启替代品 Win32DiskImager 无设备 无盘符 无u盘 无优盘 解决方案 之diskpart
    delphi Integer overflow
    MSBuild Tools offline
    delphi synedit免费的拼写检查器dll
    git 自定义命令行
    lua编译
    gcc ar
    Windows Subsystem for Linux (WSL)挂载移动硬盘U盘 卸载 c d 盘
  • 原文地址:https://www.cnblogs.com/xuan52rock/p/4763141.html
Copyright © 2011-2022 走看看