dbcp的配置

tomcat的 配置,进入conf->context.xml

<Resource name="mysql"
    auth="Container" type="javax.sql.DataSource"
    driverClassName="com.mysql.jdbc.Driver"
    url="jdbc:mysql://localhost:3306/test"
    username="root"
    password="123456"
    maxActive="100"//最大活动数
    maxIdle="30"//最大的空闲
    maxWait="10000" //最大的等待时间
     />

web中调用

Context c=new InitialContext();
        DataSource ds=(DataSource)c.lookup("java:comp/env/mysql");
         out.println(ds.getConnection());

通过注记获取

@Resource(name="mysql",type=DataSource.class,authenticationType=AuthenticationType.CONTAINER)
public class Test extends HttpServlet {

    @Resource(name="mysql")
    private DataSource ds;
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        try {
            Context c=new InitialContext();
            out.println(ds.getConnection().toString());
        } catch (NamingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        out.flush();
        out.close();
    }

原文地址:https://www.cnblogs.com/danmao/p/4038572.html