1.确保mysql-connector-java-3.1.11-bin.jar在tomcat/lib目录下。
2.在tomcat/conf/Catalina/localhost下面添加你的工程名的xml文件 。 比如 你的工程名为a那么就是a.xml
3.在a.xml中键入内容
<Context path="/DBTest" docBase="DBTest"
debug="5" reloadable="true" crossContext="true">
<Resource name="haha" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="root" password="root" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/test"/>
</Context>
其中 name是名字 , 随便起的 , 后面调用的时候需要使用 , 剩下的就修改用户名、密码、和数据库名就行了。
4.在工程的web.xml中添加
<resource-ref>
<res-ref-name>haha</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
其中 res-ref-name就是你前面起的名字.
5.在jsp或者是servlet中调用就行了。
Context ctn = new InitialContext();
DataSource ds = (DataSource)ctn.lookup("java:comp/env/haha");
Connection conn = ds.getConnection();
//下面干剩下的。
//得到的数据源是单例模式的 。 不管多少个人访问 , 都是那个数据源。