使用Tomcat数据源的方式访问数据库(MySql) --Struts2框架应用与开发

时间:2023-03-09 03:01:18
使用Tomcat数据源的方式访问数据库(MySql) --Struts2框架应用与开发

1、为方便测试首先创建数据库和表,然后插入测试数据

使用Tomcat数据源的方式访问数据库(MySql) --Struts2框架应用与开发

使用Tomcat数据源的方式访问数据库(MySql) --Struts2框架应用与开发

使用Tomcat数据源的方式访问数据库(MySql) --Struts2框架应用与开发 使用Tomcat数据源的方式访问数据库(MySql) --Struts2框架应用与开发

2、打开Tomcat服务器安装目录的conf/下的context.xml,配置context.xml文件。

使用Tomcat数据源的方式访问数据库(MySql) --Struts2框架应用与开发

在<Context>标签里加入<Resource/>标签及相关属性

 <Resource
name="jdbc/Struts2DB"
auth="Container"
type="javax.sql.DataSource"
username="root"
password="123456"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/mydata"
maxActive="8"
maxIdle="4" />

name:数据源名称

auth:连接池管理方式

type:资源类型

maxActive:连接池的最大连接数

maxIdle:连接池中最多可空闲的连接数

3、配置web.xml,在项目文件web.xml中添加指向

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

注意:

<res-ref-name>标签里的内容要和context.xml中<Resource>标签中name属性的值对应

<res-type>标签里的内容要和context.xml中<Resource>标签中type属性的值对应

<res-auth>标签里的内容要和context.xml中<Resource>标签中auth属性的值对应

4、测试连接数据库是否正常。

testDataSource.jsp:

 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<%@page import="java.sql.*,javax.sql.DataSource,javax.naming.*"%>
<%
try {
Context iniContext = new InitialContext();//初始化查找命名空间
DataSource ds = (DataSource) iniContext
.lookup("java:comp/env/jdbc/Struts2DB");//创建数据源对象,java:comp/env是固定路径,jdbc/Struts2DB是要查找的数据源名称
Connection conn = ds.getConnection();//获取连接对象
String sql = "select *from stu";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
out.print("用户名:" + rs.getString("name")+"<br/>");
out.print("密码:" + rs.getString("password")+"<br/>");
out.print("------------------------------------------<br/>");
}
out.print("使用DataSource操作数据库成功");
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
out.print(e);
}
%>
<!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> </body>
</html>

使用Tomcat数据源的方式访问数据库(MySql) --Struts2框架应用与开发