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>
3、建立数据库如下
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()); } } }
5、web.xml的配置<?xml version="1.0" encoding="UTF-8&鳎溻趄酃quot;?><web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>hello</servlet-name> <servlet-class>test.hello</servlet-class> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/servlet/hello</url-pattern> </servlet-mapping>
6、测试如下