一、在Servers中找到context.xml文件
在<context>标签之间添加以下代码:
<Resource
name="jdbc/test" <!-- 任意,但要和resource-ref里的res-ref-name一样 -->
auth="Container" <!-- 没有搜到什么意思,,但是都是这么写 -->
type="javax.sql.DataSource" <!-- 应该是资源类型吧 -->
maxActive="50" <!-- 连接池在同一时刻内所提供的最大活动连接数。 -->
maxIdle="30" <!-- 连接池在空闲时刻保持的最大连接数. -->
maxWait="10000" <!-- 发生异常时数据库等待的最大毫秒数 (当没有可用的连接时). -->
username="数据库用户名"
password="数据库密码"
driverClassName="com.mysql.jdbc.Driver" <!-- JDBC 所用到的数据库驱动的类全名. -->
url="jdbc:mysql://localhost/test?serverTimezone=UTC" > <!-- 连接至驱动的URL. -->
二、在项目文件中的WebConntent(有的是WebRoot目录)下的WEB-INF中的web.xml文件中添加以下代码:
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/test</res-ref-name> <!-- 要和Resource里面的name一样 -->
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
三、写一个测试jsp文件:
<%@ page import="javax.naming.*,javax.sql.DataSource" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>
<%
try{
Context initContext = new InitialContext();
Context envContext= (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/test");
System.out.println(ds.getConnection());
%>
通过数据源获取数据连接
<%
}catch (Exception e){
%>
连接失败
<%=e %>
<%
}
%>
</body>
</html>
四、结果