1、 把数据库JDBC驱动拷贝到%TOMCAT_HOME%/common/lib和%TOMCAT_HOME%/webapps/demo/WEB-INF/lib下(demo为web应用目录) 。
2、 修改%TOMCAT_HOME%/conf/server.xml文件,添加应用的数据源内容,如下内容所示:
<Server>
<Service name="Catalina">
<Connector ……/>
<Engine ..>
<Host appBase="webapps" name="localhost">
<Context path="/demo">
<Resource name="jdbc/mysqldb" type="javax.sql.DataSource" username="root" password="password" driverClassName="com.mysql.jdbc.Driver" maxIdle="2" maxWait="5000" url="jdbc:mysql://localhost:3306/demo" maxActive="4"/>
</Context>
</Host>
</Engine>
</Service>
</Server>
以上内容根据大家的具体情况进行相应修改,比如:把name="jdbc/mysqldb"中的mysqldb改成你所想要的名称,把数据库的连接信息改成你自己的数据信息。
3、 修改%TOMCAT_HOME%/webapps/demo/WEB-INF下的web.xml文件,在<web-app></web-app>之间添加以下内容:
3、 修改%TOMCAT_HOME%/webapps/demo/WEB-INF下的web.xml文件,在<web-app></web-app>之间添加以下内容:
<resource-env-ref>
<resource-env-ref-name>jdbc/mysqldb</resource-env-ref-name>
<resource-env-ref-type>javax.sql.DataSource</resource-env-ref-type> </resource-env-ref>
或者
<resource-ref>
<res-ref-name>jdbc/mysqldb</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
mysqldb根据具体情况做相应的修改。
4、 测试你的数据源
编写jsp文件,部署,启动并运行,看结果是否成功。
<%@ page contentType="text/html; charset=gb2312" %>
<%@ page import="javax.naming.*" %>
<%@ page import="javax.sql.*" %><%@ page import="java.sql.*" %>
<html>
<head><title>DataSource Test</title></head>
<body>
<%
Connection conn=null;
try{
Context initCtx=new InitialContext();
DataSource ds=(DataSource)initCtx.lookup("java:comp/env/jdbc/mysqldb");
if(ds!=null){
out.println("已经获得DataSource");
out.println(ds.toString());
conn=ds.getConnection();
if(conn != null){
out.println("已经获得数据库链接:"+conn);
}
conn.close();
}
}catch(Exception e){
out.println(e.toString());
System.out.println(e.toString());
}finally{
try{
try{
If(conn != null)conn.close();
}catch(SQLException ex){
ex.printStactrace();
}
}
%>
</body>
</html>
本文详细介绍如何在Tomcat服务器中配置MySQL数据源,包括复制JDBC驱动、修改server.xml和web.xml文件,并提供测试数据源正确性的示例代码。
1224

被折叠的 条评论
为什么被折叠?



