카테고리 없음

JDNI

bo97037 2015. 3. 25. 12:41

 


JNDI쓰는 법
tomcat의 server.xml에 추가한다.


<Context docBase="MyWeb" path="/MyWeb" reloadable="true" source="org.eclipse.jst.jee.server:MyWeb"/><Context docBase="education" path="/education" reloadable="true" source="org.eclipse.jst.jee.server:education">
     

      <!-- 이부분에 아래 Resource를 추가한다...-->
      <Resource name="jdbc/myoracle" auth="Container"
              type="javax.sql.DataSource" driverClassName="oracle.jdbc.OracleDriver"
              url="jdbc:oracle:thin:@127.0.0.1:1521:XE"
              username="scott" password="tiger" maxActive="20" maxIdle="10"
              maxWait="-1"/>

      </Context></Host>
    </Engine>
  </Service>
</Server>

project의 web-inf web.xml에 아래 부분을 추가한다.

<resource-ref>부분을 추가한다.

 


  <resource-ref>
    <description>Oracle Datasource example</description>
    <res-ref-name>jdbc/myoracle</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
  </resource-ref>

 

 

DBUtil부분에 아래 코드를 삽입한다...
package Util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class DBUtil {

 public static Connection getConnection() {
  Connection conn = null;

  Context initContext;
  try {
   initContext = new InitialContext();
   Context envContext = (Context) initContext.lookup("java:/comp/env");
   DataSource ds = (DataSource) envContext.lookup("jdbc/myoracle");
   conn = ds.getConnection();

  } catch (NamingException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

  return conn;
 }