(1) 第一步 Jndi配置
在Tomcat根目录/conf/context.xml文件中<Context>节点中添加<Resource> 信息内容如下
<!-- The contents of this file will be loaded for each web application -->
<Context> <!-- Default set of monitored resources -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<!-- Uncomment this to disable session persistence across Tomcat restarts -->
<!-- <Manager pathname="" /> -->
<Resource name="jdbc/bin" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="sa" password="" driverClassName="com.microsoft.jdbc.sqlserver.SQLServerDriver" url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs" />
</Context>
将用于数据连接的架包如mssqlserver2.jar复制到Tomcat根目录的/lib 目录下
第二步应用程序中的Web.xml文件配置信息内容如下
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<resource-ref>
<res-ref-name>jdbc/bin</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
<welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list></web-app>
第三步 连接获取Connection 连接
导包import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
Context ic = new InitialContext(); DataSource source = (DataSource) ic.lookup ("java:comp/env/jdbc/bin"); conn = source.getConnection();
简单应用程序可到我的字样里下载