第一步
在\conf\server.xml文件夹中找到标签并加入一个标签,这个标签配置如下:
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="1234"
maxActive="200"
maxIdle="50"
maxWait="3000"/>
第二步
在\conf\Catalina\localhost中建立一个webdemo.xml文件(webdemo和项目名字相同),然后在webdemo.xml文件输入如下内容
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/webdb?characterEncoding=UTF-8"
username="root"
password="1234"
maxActive="200"
maxIdle="50"
maxWait="3000"/>
第三步
在WEN-INF文件夹中的lib文件夹中添加mysql-connector-java-5.1.18-bin.jar架包
第四步
在项目中的web.xml中添加如下代码
ViewDictionary
ViewDictionary
ViewDictionary
/servlet/ViewDictionary
注:ViewDictionary是需要运行的servlet的类名
第五步
在ViewDictionary类中测试,代码如下
public class ViewDictionary 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();
// 根据webdb数据源获得DataSource对象
javax.sql.DataSource ds = (javax.sql.DataSource) ctx
.lookup("java:/comp/env/jdbc/webdb");
Connection conn = ds.getConnection();
// 执行SQL语句
PreparedStatement pstmt = conn
.prepareStatement("SELECT * FROM t_dictionary");
ResultSet rs = pstmt.executeQuery();
StringBuilder table = new StringBuilder();
table.append("
table.append("
书名价格");while (rs.next()) // 生成查询结果
{
table.append("
" + rs.getString("english") + "");table.append(rs.getString("chinese") + "
");}
table.append("
");out.println(table.toString()); // 输出查询结果
pstmt.close(); // 关闭PreparedStatement对象
}
catch (Exception e)
{
out.println(e.getMessage());
}
}
}
原文:http://www.cnblogs.com/chen-c/p/4635565.html