当前位置:Gxlcms > 数据库问题 > Tomcat数据库连接池配置

Tomcat数据库连接池配置

时间:2021-07-01 10:21:17 帮助过:7人阅读

auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="root" password="123456" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/t1" />

我的database名是:t1
table名是:bnutalk
用户名是root
密码是123456
你只要修改对应的地方就可以了,添加后效果如下:
技术分享

(2)修改web.xml

技术分享

在webapp的结束标签之前加入:

<resource-ref>
      <description>DB Connection</description>
      <res-ref-name>jdbc/t1</res-ref-name>
      <res-type>javax.sql.DataSource</res-type>
      <res-auth>Container</res-auth>
  </resource-ref>

将t1改成你的数据库名就行了。
技术分享



测试是否配置成功

(1)新建一个Serve和一个Dynamic Web Project项目

技术分享

(2)new一个jsp文件,名字任意

技术分享

index.jsp代码如下:

<%@ page language="java" contentType="text/html" 
pageEncoding="GBK" import="java.sql.*,javax.sql.*,javax.naming.*"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%

  Context ctx=new InitialContext();

  Connection conn=null;

  DataSource ds=(DataSource)ctx.lookup("java:comp/env/jdbc/t1");

  conn=ds.getConnection();

  Statement stmt=conn.createStatement();

  ResultSet rs=stmt.executeQuery("select id,age from bnutalk");

  while(rs.next()){

      System.out.println(rs.getInt("id")+","+rs.getInt("age")); 
  }

  rs.close();

  stmt.close();

  conn.close();   

 %>
</body>
</html>
(3)在src下,new一个包,再new一个Servlet。

技术分享

Serverlet代码如下:

package com.imooc.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class MyServlet
 */
@WebServlet("/MyServlet")
public class MyServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public MyServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    this.doGet(request, response);
    }

}

我的t1数据库中的bnutalk表的内容是:
技术分享

下面来看看输出的内容是否和数据库中的吻合:
右键web项目->run on server
输出结果如下:
技术分享

ok,到此为止,Tomcat的数据库连接池就配置成功了。

Tomcat数据库连接池配置

标签:

人气教程排行