您的位置:首页 > 运维架构 > Tomcat

tomcat配置数据源DataSource

2013-06-24 22:55 495 查看
学习servlet&jsp的过程中进行DataSource的配置。通过截图来说明吧!!!通过截图直截了当的学习肯定容易懂的。

实验所用IDE为eclipse

配置分三步就可以了

1、在工程下的META-INF下新建文件context.xml,文件内容如下:




<?xml version="1.0" encoding="UTF-8"?>
<Context
debug="5"
reloadable="true">
<Resource
name="jdbc/lib"
auth="Container"
driverClassName="com.mysql.jdbc.Driver"
maxActive="100"
maxIdle="30"
maxWait="10000"
password="793502240"
type="javax.sql.DataSource"
url="jdbc:mysql://localhost:3306/library?autoReconnect=true"
username="root" />
</Context>

1和2步骤中注意的是name和<res-ref-name></res-ref-name>的值要一样

2、在web.xml中注册,在<web 中添加如下代码





<resource-ref>
<res-ref-name>jdbc/lib</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>


3、取得连接

public Database() {
try{
Context init = new InitialContext();
Context con = (Context) init.lookup("java:/comp/env");
ds = (DataSource) con.lookup("jdbc/lib");
System.out.println("成功");
// 获取直接java:/comp/env/jdbc/lib
}catch(NamingException e) {
System.out.println("出错了");
e.printStackTrace();
}
}
/**
* 获取数据库连接
* @return
*/
public Connection getConnection() {
if(con == null){
try {
if(ds != null )
con = ds.getConnection();
else
System.out.println("null ds");
} catch (SQLException e) {
System.out.println("找不到连接");
e.printStackTrace();
}
}
return con;
}


剩下的其他数据库查、删、改、插操作就简单多了,在此就不说了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息