具体操作过程:
1、配置全局数据库连接池
在<tomcat安装目录>\conf\server.xml文件中找到<GlobalNamingResources>标签,添加下列配置:
<Resource name="jdbc/webdb"
auth="Container"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/webdb?characterEncoding=UTF-8"
username="root"
password="root"
maxActive="200"
maxIdle="50"
maxWait="3000" />
2、下载JDBC驱动的jar包,放在tomcat的lib目录下
3、在创建的webdemo工程中web.xml文件中增加下列配置:
<resource-ref>
<res-ref-name>jdbc/webdb</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
4、在webdemo工程的META-INF目录下增加一个context.xml文件,内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Listener className="org.apache.catalina.startup.TldConfig"/>
<Listener className="org.apache.catalina.startup.TldConfig"/>
<Listener className="org.apache.catalina.startup.TldConfig"/>
<Listener className="org.apache.catalina.startup.TldConfig"/>
<Resource
auth="Container"
description="webdb"
name="jdbc/webdb"
password="root"
username="root"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/webdb?characterEncoding=UTF-8" />
</Context>
5、访问数据库事例java文件
package chapter4;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Helloworld extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
try
{
javax.naming.Context ctx = new javax.naming.InitialContext();
javax.sql.DataSource ds = (javax.sql.DataSource)ctx.lookup("java:/comp/env/jdbc/webdb");
Connection conn = ds.getConnection();
PreparedStatement pst = conn.prepareStatement("SELECT * FROM t_dictionary");
ResultSet rs = pst.executeQuery();
StringBuilder table = new StringBuilder();
table.append("<table border='1'>");
table.append("<tr><td>eg-name</td><td>ch-name</td></tr>");
while(rs.next())
{
table.append("<tr><td>"+rs.getString("english")+"</td><td>");
table.append(rs.getString("chinese")+"</td></tr>");
}
table.append("</table>");
out.println(table.toString());
pst.close();
}
catch(Exception e)
{
out.println(e.getMessage());
}
}
}
差不多servlet访问mysql数据库能测试成功。