2011년 8월 2일 화요일

Tomcat JNDI Datasource 설정(MySQL)

출처: http://tomcat.apache.org/tomcat-6.0-doc/jndi-datasource-examples-howto.html


1. server.xml 파일에 resource 추가
(1) context 아래에 resource 추가하기
<Context path="/DBTest" docBase="DBTest" debug="5" reloadable="true" crossContext="true">
  <Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
               maxActive="100" maxIdle="30" maxWait="10000"
               username="javauser" password="javadude" driverClassName="com.mysql.jdbc.Driver"
               url="jdbc:mysql://localhost:3306/javatest"/></Context>

(2) GlobalNamingResources 에 추가
    <GlobalNamingResources>
        <Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
            name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase" />
        <Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource" 
            maxActive="100" maxIdle="30" maxWait="10000" username="javauser" password="javadude"
            driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/javatest" />
    </GlobalNamingResources>

...

<Context path="/DBTest" docBase="DBTest" debug="5" reloadable="true" crossContext="true">
  <ResourceLink global="jdbc/TestDB" name="jdbc/TestDB" type="javax.sql.DataSource"/>
</Context>


2. web.xml 파일 수정 
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">
  <description>MySQL Test App</description>
  <resource-ref>
      <description>DB Connection</description>

      <res-ref-name>jdbc/TestDB</res-ref-name>
      <res-type>javax.sql.DataSource</res-type>
      <res-auth>Container</res-auth>
      </resource-ref>
</web-app>


3. test.jsp  

<%@ page import="java.sql.*"%>
<%@ page import="javax.naming.*" %>
<%@ page import="javax.activation.*" %>
<%
    InitialContext cxt = new InitialContext();
    javax.sql.DataSource ds = null;
    Connection conn = null;
        if ( cxt == null ) {
       throw new Exception("Uh oh -- no context!");
    }
    ds = (javax.sql.DataSource) cxt.lookup( "java:/comp/env/jdbc/TestDB" );
    if ( ds == null ) {
       throw new Exception("Data source not found!");
    }
    conn = ds.getConnection();
    out.println(conn.getMetaData().getDriverVersion());
%>


댓글 없음:

댓글 쓰기