미들웨어 및 웹서버/톰캣(Tomcat)

Tomcat 6 에서 jndi 설정 아주 간단한 예제

후바스탱크 2013. 12. 24. 18:10

※ ojdbc14.jar 다운로드

ojdbc14.jar



1. context.xml 에 기술

<Environment name="SYSTEM_NAME" type="java.lang.String" value="real"/>


<Resource name="jdbc/OracleTest"

auth="Container"

type="oracle.jdbc.pool.OracleDataSource"

driverClassName="oracle.jdbc.driver.OracleDriver"

factory="oracle.jdbc.pool.OracleDataSourceFactory"

url="jdbc:oracle:thin:@localhost:1521:orcl"

user="test"

password="test"

maxActive="20"

maxIdle="10"

maxWait="-1" />


2. 테스트 jsp 페이지 

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>

<%@ page import="java.sql.*"%>
<%@ page import="javax.sql.*"%>
<%@ page import="javax.naming.*"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>JNDI Test</title>
</head>
<body>
<%
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;

try {
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:/comp/env");
DataSource ds = (DataSource) envCtx.lookup("jdbc/OracleTest");
String name = (String)envCtx.lookup("SYSTEM_NAME");

conn = ds.getConnection();

out.write("<p>Context Lookup :" + name + " </p>");
out.write("<p>DB Connection..</p>");

String sQuery = "SELECT * FROM TEST1";
stmt = conn.createStatement();
rs = stmt.executeQuery(sQuery);

while (rs.next()) {
out.write(rs.getString(1) + "<br />");
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (rs != null)
try {
rs.close();
} catch (Exception ex2) {
}
if (stmt != null)
try {
stmt.close();
} catch (Exception ex3) {
}
if (conn != null)
try {
conn.close();
} catch (Exception ex4) {
}
}
%>
</body>
</html>


간단히 설명 하자면 java:/comp/env 를 통하여 context 객체를 생성 할 수 있고


context.xml 에 기술되어있는 Resource 를 통하여 다음과 같이 DataSource 객체를 얻을 수가 있고

DataSource ds = (DataSource) envCtx.lookup("jdbc/OracleTest");


context.xml 에 기술되어있는 Environment 를 통하여 다음과 같이 환경변수를 읽어 들일 수가 있다.

String name = (String)envCtx.lookup("SYSTEM_NAME");