1、在Tomcat的安装目录 apache-tomcat\conf\server.xml 中找到<GlobalNamingResources>标签,并加入一个子标签<Resource>具体配置如下: <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、在Tomcat的安装目录 apache-tomcat\conf\Catalina\localhost中建立一个wx.xml文件 内容如下<Context path="/wx" docBase="wx" debug="0"><ResourceLink name="jdbc/webdb" global="jdbc/webdb" type="javax.sql.DataSource"/></Context>

4、建立web工程如下package test;import java.io.IOException;import java.io.PrintWriter;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class hello 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 pstmt=conn.prepareStatement("select*from t_dictionary"); ResultSet rs=pstmt.executeQuery(); StringBuilder table=new StringBuilder(); table.append("<table border='1'>"); table.append("<tr><td>书名</td><td>价格</td><tr>"); while(rs.next()){ table.append("<tr><td>"+rs.getString("english")+"</tr></td>"); table.append("<tr><td>"+rs.getString("chinese")+"</td></tr>"); } table.append("</table>"); out.println(table.toString()); pstmt.close(); } catch (Exception e) { out.println(e.getMessage()); } } }
