当前位置: 代码迷 >> 综合 >> JAVA Web08——JNDI_连接池
  详细解决方案

JAVA Web08——JNDI_连接池

热度:27   发布时间:2024-03-08 13:04:07.0

一、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);}
    }