JNDI:如何在TOMCAT中配置數據源通過JNDI訪問測試操作步驟

JNDI:Java Naming and Directory Interface
中文翻譯:Java命名和目錄接口
實現功能:在Tomcat中配置Mysql數據源,然後通過JNDI測試工程測試是否配置成功
開發環境:MyEclipse5.0GA Tomcat/5.5.12

接下來的就是操作步驟:
1〉在Mysql中Test數據庫中創建表student
use test;
create table student(
id int not null primary key,
name varchar(20)
);

--添加三條測試數據:
insert into student values
(1,'張三'),
(2,'李四'),
(3,'王五');

--查看是否添加成功:
select * from student;

數據層完成之後,我們開始創建JNDI測試工程。

2〉在MyEclipse中創建工程jndiTest080220,編輯WEB-INF/web.xml文件,在文件中添加:
<description>MYSQL JNDI TEST</description>
<resource-ref>
<description>DB Connection test</description>
<res-ref-name>jdbc/test</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
在WebRoot下新建一個MyJsp.jsp頁面,添加以下代碼:
<h1>get data from mysql's db named test </h1>
<hr>
<%
DataSource ds = null;
try {
Context initCtx = new InitialContext();
if (initCtx == null)
throw new Exception("Initial Failed!");
Context ctx = (Context) initCtx.lookup("java:comp/env");
if (ctx != null)
ds = (DataSource) ctx.lookup("jdbc/test");
if (ds == null)
throw new Exception("Look up DataSource Failed!");
} catch (Exception e) {
System.out.println(e.getMessage());
}
%>
<%
Connection conn = ds.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from student");
while (rs.next()){
%>
<%=rs.getInt(1) %>
<%=rs.getString(2) %>
<%
}
rs.close();
stmt.close();
conn.close();
%>
web.xml和MyJsp.jsp代碼編寫完畢之後,我們最後來配置TOMCAT數據源且同時發佈我們的工程。

3〉在$tomcat$\Tomcat 5.5\conf\server.xml,對server.xml文件進行編輯,
在<Host></Host>之間添加:
<Context path="/jdniTest080220" debug="0" reloadable="true" privileged="true" docBase="E:\HNHJ\java\jndiTest080220" workDir="E:\HNHJ\java\jndiTest080220\WebRoot">
<Resource
name="jdbc/test"
auth="Container"
type="javax.sql.DataSource"
driverClassName="org.gjt.mm.mysql.Driver"
url="jdbc:mysql://localhost:3306/test"
username="root"
password=""
maxActive="20"
maxIdle="10"
maxWait="10000" />
</Context>
注意:$tomcat$表示你當前安裝tomcat的根目錄

4〉啓動tomcat,在IE中輸入URL:http://localhost:8080/jdniTest080220/WebRoot/MyJsp.jsp


備註:
1.如果頁面報“javax.servlet.ServletException: Cannot load JDBC driver class 'org.gjt.mm.mysql.Driver'
”錯誤,解決方法是在“$tomcat$\Tomcat 5.5\common\lib”下添加mysql-connector-java-3.0.17-ga-bin.jar
2.如果頁面報“javax.servlet.ServletException: Cannot create JDBC driver of class '' for connect URL 'null'
”錯誤,說明你發佈工程的方式是通過MyEclipse直接發佈上去,然後啓動服務進行訪問的,解決方法是按照3〉的方式配置<Context>指定工程文件夾物理路徑方式進行發佈。
3.web.xml文件中res-ref-name名稱:jdbc/test和3〉中<Resource name="jdbc/test" ...>必須一致。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章