Tomcat的conf/context.xml中的配置
<Context>
<Resource name="jdbc/news"
auth="Container"type="javax.sql.DataSource" maxActive="100"
maxIdle="30" maxWait="10000" username="sa" password=“sa"
driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
url="jdbc:sqlserver://localhost:5545;DatabaseName=NewsManager"/>
</Context>
在web.xml中配置<resource-ref>
<resource-ref>
<res-ref-name> jdbc/news </res-ref-name>
<res-type> javax.sql.DataSource </res-type>
<res-auth> Container </res-auth>
</resource-ref>
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class BaseDao {
public Connection getConnection () {
Context ctx;
try {
ctx = new InitialContext();
//获取与逻辑名相关联的数据源对象
DataSource ds=(DataSource)ctx.lookup("java:comp/env/jdbc/news");
conn=ds.getConnection();
} catch (SQLException exception) {
exception.printStackTrace();
}catch (NamingException namingException)
namingException.printStackTrace();
}
}
}