1、把数据库驱动包 copy 到 %CATALINA_HOME%\common\lib 下。
2、修改 %CATALINA_HOME%\conf\server.xml 文件,在 <Host> 节点下添加:
(或者在 %appName%\META-INF 下建立 context.xml,内容为上面的代码。)
3、修改 web.xml,在 <web-app> 节点下添加:
(这一步不添加页没问题。)
4、在代码中获取数据库连接:
2、修改 %CATALINA_HOME%\conf\server.xml 文件,在 <Host> 节点下添加:
1
2
3
4
5
6
7
8
9
|
<!-- appName 为项目名 --!>
<
Context
path
=
"/appName"
docBase
=
"appName"
auth
=
"Container"
>
<
Resource
name
=
"jdbc/MySQLDS"
scope
=
"Shareable"
type
=
"javax.sql.DataSource"
url
=
"jdbc:mysql://localhost:3306/test?useUnicode=true&charact-erEncoding=GBK"
driverClassName
=
"com.mysql.jdbc.Driver"
username
=
"root"
password
=
"111111"
maxWait
=
"3000"
maxIdle
=
"100"
maxActive
=
"10"
/>
</
Context
>
|
(或者在 %appName%\META-INF 下建立 context.xml,内容为上面的代码。)
3、修改 web.xml,在 <web-app> 节点下添加:
1
2
3
4
5
6
|
<
resource-ref
>
<
description
>Oracle Datasource example</
description
>
<
res-ref-name
>MySQLDS</
res-ref-name
>
<
res-type
>javax.sql.DataSource</
res-type
>
<
res-auth
>Container</
res-auth
>
</
resource-ref
>
|
(这一步不添加页没问题。)
4、在代码中获取数据库连接:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
import
java.sql.Connection;
import
javax.naming.Context;
import
javax.naming.InitialContext;
import
javax.sql.DataSource;
public
class
DBUtil {
public
Connection getConnection()
throws
Exception {
Context context =
new
InitialContext();
// 获取数据源
DataSource ds = (DataSource) context.lookup(
"java:comp/env/jdbc/MySQLDS"
);
// 获取数据库连接
Connection conn = ds.getConnection();
if
(conn !=
null
&& !conn.isClosed()) {
return
conn;
}
else
{
return
null
;
}
}
}
|