JAVA Web08——JNDI_连接池

一、JNDI

JNDI:java命名与目录接口(Java Naming and Directory Interface)

将某一个资源(对象),以配置文件(tomcat/conf/context.xml)的形式写入;

实现步骤

tomcat/conf/context.xml配置:

<Environment name="jndiName" value="jndiValue" type="java.lang.String" />

jsp中用:

<%
    Context ctx = new InitialContext();
    String testJndi = (String)ctx.lookup("java:comp/env/jndiName");
    out.print(testJndi);
%>

二、连接池

初衷:打开、关闭数据库比较消耗性能
在连接池中有与数据库进行通信的常驻链接  

常见连接池:Tomcat-dbcp、dbcp、c3p0、druid
可以用数据源(java.sql.DataSource)管理连接池

Tomcat-dbcp:

  1. 类似jndi,在content.xml中配置数据库
    <Resource name="student" auth="Container" type="javax.sql.DataSource"
                  maxActive="400" maxIdle="30" maxWait="5000"
                  username="root" password="123456" driverClassName="com.mysql.cj.jdbc.Driver"
                  url="jdbc:mysql://localhost:3306/stx15?serverTimezone=UTC"/>

    name:Resource的jndi名字,可以有多个连接池
    auth:指定Resource的管理者,共有两个可选值:Container和 Application
              Container:由容器来创建 Resource
              Application:由Web应用来创建和管理 Resource

    Type:指定Resource的类型
    maxActive:指定连接池中,处于活动状态的数据库连接的最大数量;如果值为0,表示不受限制
    maxIdle:指定连接池中,处于空闲状态的数据库连接的最大数量;如果值为0,表示不受限制
    maxWait:指定连接池中,连接处于空闲状态的最长时间(单位是毫秒),如果超出此最长时间将会抛出异常。如果值为-1,表示允许无限制等待。
    username:访问数据库的用户名
    password:访问数据库的密码
    diverClassName:指定连接数据库的驱动程序的类名
    url:指定连接数据库的URL

  2. 在项目的web.xml中

    <resource-ref>
        <res-ref-name>student</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Cotainer</res-auth>
    </resource-ref>
  3. 测试应用

    public class JndiDemo {
        public static void Test(){
            try{
                Class.forName("com.mysql.cj.jdbc.Driver");
                Connection con = null;
                Context ctx = new InitialContext();
                DataSource ds = (DataSource)ctx.lookup("java:comp/env/student");
                con = ds.getConnection();
                System.out.println("ok");
            } catch (NamingException | SQLException | ClassNotFoundException e){
                e.printStackTrace();
            }
        }
    }
    @WebServlet(name = "MyServlet",urlPatterns = "/MyServlet")
    public class MyServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            System.out.println("doPost");
            JndiDemo.Test();
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            System.out.println("doGet");
            this.doPost(request,response);
        }
    }

     

     

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值