今天花了两个钟头,终于把tomcat的数据库连接池弄好。好高兴。。。。现在把它整理到博客上来做个备份。。。。。免得以后忘记。。。。我脑筋不好使。。。。容易犯傻。。。。发浑啦。。。。呵呵。。。下来进入话题:
1.首先在$tomcat/conf/server.xml($tomcat 表示tomcat的安装目录)中的<GlobalNamingResources></GlobalNamingResources>之间加上数据库连接池的配置。具体如下:
<Resource
name="java/mysql"
type="javax.sql.DataSource"
password="123456"
driverClassName="com.mysql.jdbc.Driver"
maxIdle="2"
maxWait="5000"
username="root"
url="jdbc:mysql://localhost:3306/userinfo"
maxActive="4"/>
也可以通过tomcat/admin来建立。。。。。。这里就不说了。。。。
2. 再在$tomcat/conf/context.xml文件中加入以下代码:
<ResourceLink
name="java/mysql"
type="javax.sql.DataSource"
global="java/mysql"/>
3. 建立一个webproject,这里我就叫test吧。。。。。修改该web工程的WebRoot/WEB-INF/web.xml文件。。。。在web.xml中添加以下代码:
<resource-ref>
<description>mysql depool haha</description>
<res-ref-name>java/mysql</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
4. 编写测试页面index.jsp。。。。
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%@ page import="javax.sql.*" %>
<%@ page import="javax.naming.*"%>
<%@ page session="false" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%
out.print("DB Test Start......<br>");
DataSource ds=null;
try{
InitialContext ctx=new InitialContext();
ds=(DataSource)ctx.lookup("java:comp/env/java/mysql");
Connection conn=ds.getConnection();
conn.close();
out.print("DB Test Success......");
}catch(Exception ex){
out.print("DB Test hava a Error....."+ex.getMessage());
ex.printStackTrace();
}
%>
</body>
</html>
好了。。。就这么多了。。。。然后部署发布。。。。在浏览器中输入:http://localhost:8080/test/index.jsp。。。。结果是如下:
DB Test Start......
DB Test Success......
这个只是我自个儿配置的方法。。。。也许不好。。。但是自己收藏起来算个锻炼和备份吧。。。。希望不要见笑。。。。。。。。。。
本文详细介绍了如何在Tomcat中配置数据库连接池,包括在server.xml和context.xml中的设置,以及在web.xml中添加资源引用的过程。
471

被折叠的 条评论
为什么被折叠?



