使用Tomcat数据库连接池全过程

本文详细介绍了如何在Eclipse环境中配置MySQL数据库和Tomcat服务器,包括添加MySQL驱动,编辑context.xml和web.xml文件,以及使用连接池创建JSP页面。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

eclipse+mysql(8.0)+tomcat(9.0)

一.在Tomcat 文件夹中的lib目录下添加MySQL驱动包.

二.编辑在servers目录下的context.xml文件:
在Context标签体中添加下面语句:

<Resource name="mldn/jdbc"
     auth="Container"
     type="javax.sql.DataSource"
     maxTotal="100"
     maxldle="30"
     maxWaitMillis="10000"
     username="root"
     password="root"
     driverClassName="com.mysql.cj.jdbc.Driver"
     url="jdbc:mysql://localhost:3306/jdbc?&amp;useSSL=false&amp;serverTimezone=UTC"
     />

额外解释:name=“mldn/jdbc” 中的jdbc表示数据库的名字为jdbc

添加后的context文件:

<?xml version="1.0" encoding="UTF-8"?>
<Context>
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
    <WatchedResource>WEB-INF/tomcat-web.xml</WatchedResource>
    <WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>

    
    <!--
    <Manager pathname="" />
    -->
    
    <Resource name="mldn/jdbc"
     auth="Container"
     type="javax.sql.DataSource"
     maxTotal="100"
     maxldle="30"
     maxWaitMillis="10000"
     username="root"
     password="root"
     driverClassName="com.mysql.cj.jdbc.Driver"
     url="jdbc:mysql://localhost:3306/jdbc?&amp;useSSL=false&amp;serverTimezone=UTC"
     />
     
     
</Context>

三.编辑项目中的WebContent目录下的WEB-INF下的web.xml文件:
添加:

<resource-ref>
    <description>DB Connection</description>
    <res-ref-name>mldn/jdbc</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
  </resource-ref>

四.编写jsp文件使用连接池:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@page import="javax.naming.*" %>
    <%@page import="javax.sql.*" %>
    <%@page import="java.sql.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String DSNAME="java:comp/env/mldn/jdbc";

Context ctx=new InitialContext();
DataSource ds=(DataSource)ctx.lookup(DSNAME);

Connection conn=ds.getConnection();

%>
  <%=conn %>
  <%conn.close(); %>

</body>
</html>

五.打开数据库,运行jsp结果:

在这里插入图片描述

成功!!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员小牧之

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值