JSP

[펌] 톰갯 5.5에서 커넥션풀을 이용하는 방법

십억10 2009. 4. 6. 10:03

톰갯 5.5에서 커넥션풀을 이용하는 방법

  1. JDBC Driver 를 $CATALINA_HOME/common/lib 에 복사한다.
  2. server.xml 의 <context> 태그 안쪽에 다음을 추가한다.
              <Resource name="jdbc/DBName"
    auth="Container"
    type="javax.sql.DataSource"
    driverClassName="com.mysql.jdbc.Driver"
    loginTimeout="10"
    maxWait="5000"
    username="아이디"
    password="비밀번호"
    testOnBorrow="true"
    url="jdbc:mysql://localhost:3306/디비이름" />
  3. web.xml 에 다음을 추가한다.
        <resource-ref>
    <description>MySQL DB Connection</description>
    <res-ref-name>jdbc/DBName</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
    </resource-ref>
  4. JSP 코드를 다음과 같이 작성한다. 관련 DB와 테이블은 작성되어 있어야 합니다.
    <%@ page contentType="text/html;charset=utf-8" session="true" %>
    <%@ page import="java.sql.*" %>
    <%@ page import="javax.sql.*" %>
    <%@ page import="javax.naming.*" %>
    <html>
    <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <title>테스트</title>
    </head>
    <body>
    <%
    DataSource ds = null;
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;

    try {
    Context initCtx = new InitialContext();
    Context envCtx = (Context) initCtx.lookup("java:comp/env");
    ds = (DataSource) envCtx.lookup("jdbc/DBName");
    conn = ds.getConnection();
    stmt = conn.createStatement();
    rs = stmt.executeQuery("select code_class_id, code_class_name from tb_code_class");
    while(rs.next()) {
    out.println("Code Class ID: " + rs.getString("code_class_id"));
    out.println(", Code Class Name: " + rs.getString("code_class_name") + "<br />");
    }
    rs.close();
    stmt.close();
    conn.close();
    } catch (Exception e) {
    out.println("<br /><font color='red'>SQL Exception: " + e + "</font><br/>");
    }
    %>
    </body>
    </html>
  5. JSTL 을 이용하는 경우에는 $CATALINA_HOME/common/lib 에 standard.jar, jstl.jar 파일을 복사하고 코드를 다음과 같이 작성합니다.
    <%@ page contentType="text/html;charset=utf-8" session="true" %>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

    <sql:query var="rs" dataSource="jdbc/DBName">
    select code_class_id, code_class_name from tb_code_class
    </sql:query>

    <html>
    <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <title>테스트</title>
    </head>
    <body>

    <c:forEach var="row" items="${rs.rows}">
    ID ${row.code_class_id}<br/>
    Name ${row.code_class_name}<br/><br/>
    </c:forEach>

    </body>
    </html>