Tomcat7连接池配制方法

有两种方法:

1.简便配制方法
在D:\Program Files\Apache Software Foundation\Tomcat 7.0\conf\server.xml文件中的<Host></Host>标签之间加入如下的Context代码


<Context path="/test" docBase="test" debug="0" reloadable="true" crossContext="true">
    <Resource name="jdbc/test" auth="Container"  type="javax.sql.DataSource" maxActive="10" maxIdle="5" maxWait="10000" username="sa" password="sasa"  driverClassName="net.sourceforge.jtds.jdbc.Driver" url="jdbc:jtds:sqlserver://localhost:1433/mydb"/>
</Context>

2.官方推荐方法

首先配置tomcat下的conf下的context.xml文件,在之间添加连接池如下:

    <Resource name="jdbc/test" auth="Container"  type="javax.sql.DataSource" maxActive="10" maxIdle="5" maxWait="10000" username="sa" password="sasa"  driverClassName="net.sourceforge.jtds.jdbc.Driver" url="jdbc:jtds:sqlserver://localhost:1433/test"/>

然后配置你的应用下的web.xml中的之间加入:

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

-----------------------------------------------------------

测试JSP页面代码:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*"%>
<%@ page import="javax.sql.*"%>
<%@ page import="javax.naming.*"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>Tomcat7连接池配制测试</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
    <%
        try {
            DataSource ds = null;
            InitialContext ctx = new InitialContext();
            ds = (DataSource) ctx.lookup("java:comp/env/jdbc/test");
            Connection conn = ds.getConnection();
            Statement stmt = conn.createStatement();
            String strsql = " select * from T1";
            ResultSet rs = stmt.executeQuery(strsql);
            while (rs.next()) {
                out.println(rs.getString(1) + "....." + rs.getString(2) + "</br>");
            }
            stmt.close();
            rs.close();
            conn.close();

        } catch (SQLException se) {
            out.print("异常:" + se.toString());
        }
    %>  
</body>
</html>

 

你可能感兴趣的:(tomcat7)