Myeclipse WEB工程JSP使用JNDI 数据库连接池连接Mysql数据库

时间:2021-06-15 19:29:49

在网上查了很多,最后实现了。下面写一下过程:

首先,在WEBROOT/META-INF下建一个文件context.xml,内容为:

<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource
name="jdbc/ConnectionPool"
auth="Application"
type="javax.sql.DataSource"
username="root"
password="root"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/sow"
maxActive="8"
maxIdle="4"/>
</Context>

其中,name属性为数据库连接池的名称,auth属性为数据库连接池的作用范围,Application为作用于本web项目;url属性的后面sow为数据库名;

其次,在web.xml中添加配置:

 <resource-ref>
<description>news DataSource</description>
<res-ref-name>jdbc/ConnectionPool</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Application</res-auth>
</resource-ref>

注意里面的属性要一致。

接着,新建MyJsp.jsp用作测试

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%@ page import="javax.naming.*" %>
<%@ page import="javax.sql.DataSource" %>
<%
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 'MyJsp.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>
<%
Context initCtx = new InitialContext();
Context ctx = (Context) initCtx.lookup("java:comp/env");
//获取连接池对象
DataSource ds =(DataSource)ctx.lookup("jdbc/ConnectionPool");
//创建连接
Connection conn = ds.getConnection();
System.out.println("conn="+conn);
Statement stmt = conn.createStatement();
String mysql="select * from notification_tb";
ResultSet myrs=stmt.executeQuery(mysql); //执行查询
%>
<body>
This is my JSP page. <br>
<table>
<%
while(myrs.next())
{
%>
<%
String notiTheme=myrs.getString("notiTheme");
String notiContent=myrs.getString("notiContent");
%>
<tr><td><%=notiTheme %></td><td><%=notiContent %></td></tr>
<%
System.out.println(notiTheme);
System.out.println(notiContent);
%>
<%
}
%>
</table>
</body>
</html>

然后重启TOMCAT,发布网站访问http://localhost:8080/PW_Application/MyJsp.jsp即可看到结果。