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?&useSSL=false&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?&useSSL=false&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结果:
成功!!