EJB學習文擋

EJB學習文擋

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

文件狀態

[  ] 草稿文件

[] 正式文件

[  ] 更改正式文件

文件標識:

 

當前版本:

1.0

    者:

宋海龍

完成日期:

200568

 

 

 

 

版本/狀態

作者

參與者

起止日期

備註

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  

 

 

 

 

 

 

 

 

 

 

 

 

 

這是一個Servlet調用SessionBeanSessionBean調用CMP的小例子,功能非常簡單,就是從數據庫中讀一條數據出來。

環境:Jbuilder9+Weblogic8.1+Oracle9i

關於環境的配置在此就不多說了,在Jb9中要把Weblogic配置好。

 

 

 

         1.              第一步當然是數據庫操作

建表,並寫入一條實驗數據。打開Oracle客戶端工具中的SQL Plus Work Sheet小工具。輸入並執行以下命令:

 

 

 

CREATE TABLE DDDD

(

DEPTNO number(10) PRIMARY KEY NOT NULL,

DNAME varchar(50),

LOC varchar(50)

);

INSERT INTO DDDD VALUES(20,'宋海龍','長沙');

 

 

 

         2.              建立一個CMP

新建一個工程,工程名爲cmpseservlet.

點擊Next,直到它變灰,點擊Finish.

 

 

 

建立一個EJB Module,取名字爲CMPBean

導入Schema .

這裏要注意的是,應該在Weblogic Console中建立好連接池和數據源。我的連接池名爲MyJDBC Connection Pool2,數據源名爲MyJDBC Data Source2,與此數據源相對應的JNDI名爲myjndi2Oracle數據庫所在的主機IP地址爲:192.168.0.7,數據庫名爲:certdb,用戶名爲:certdb

下面配置數據庫的連接以及JNDI名。

配置成功以後,Jbulder將影射數據庫的表

選擇DDDD表點右鍵,新建Create CMP 2.0 EntityBean

選擇inferfaces選項,選擇local/Remote

這樣一個CMP就建成了,編譯並部署這個實體Bean。當然要部署Bean的話,首先要啓動Weblogic服務器才行,在此不妨先建立一個啓動WeblogicServer的運行信息。點擊Run菜單的Run Project,出現如下對話框

New按鈕,出現下圖

在此配置一個Server

Ok這樣就配置好了服務器運行信息,即在Jb中可以直接啓動服務器了。

 

 

 

下邊我們新建一個測試程序來測試一下這個CMP

選擇新建EJB Test Client

main函數的DdddTestClient1 client = new DdddTestClient1();後面添加如下代碼:

System.out.println("===========START==============");

DdddRemoteHome home = client.getHome();

try{

DdddRemote r = home.findByPrimaryKey(new java.math.BigDecimal(20));

System.out.println(r.getDeptno());

System.out.println(r.getDname());

System.out.println(r.getLoc());

System.out.println("============END=============");

}

catch(Exception ex) {

ex.printStackTrace();

}

 

 

 

運行測試客戶端,成功後顯示下列結果:

 

 

 

 

 

 

         3.              建立一個Stateless SessionBean

選擇File菜單的New子菜單,出現如下

新建一個SessionBean Module,名字爲SesDDDD

新建一個SessionBean,如下圖

給這個SessionBean取名字爲SesDDDD

選擇interfaces選項,選擇local/Remote

 

 

 

添加greet方法,returnType :Stringinterfaces選項爲local/Remote

Jb將自動在SesDDDD接口中添加greet() 方法

package cmpseservlet;

 

 

 

import javax.ejb.*;

import java.util.*;

import java.rmi.*;

 

 

 

public interface SesDDDD extends javax.ejb.EJBObject {

public String greet() throws RemoteException;

}

Jb也將自動在SesDDDDLocal接口中添加greet() 方法

 

 

 

package cmpseservlet;

 

 

 

import javax.ejb.*;

import java.util.*;

 

 

 

public interface SesDDDDLocal extends javax.ejb.EJBLocalObject {

public String greet();

}

修改SesDDDDBean類中greet方法,修改以後爲:

public String greet() {

/**@todo Complete this method*/

try {

//get naming context

Context context = getInitialContext();

 

 

 

//look up jndi name

Object ref = context.lookup("DdddRemote");

//look up jndi name and cast to Home interface

DdddRemoteHome ddddRemoteHome = (DdddRemoteHome) PortableRemoteObject.

narrow(ref, DdddRemoteHome.class);

return ddddRemoteHome.findByPrimaryKey(new java.math.BigDecimal(50)).getDname().

toString();

}

catch (Exception e) {

e.printStackTrace();

}

 

 

 

return "=============error===========";

}

需要注意的是,要在頭上加入這幾個包

import javax.naming.Context;

import java.util.*;

import javax.rmi.*;

 

 

 

修改SesDDDDBean類中getInitialContext方法,修改以後爲:

 

 

 

//getInitialContext()爲新加的

private Context getInitialContext() throws Exception {

 

 

 

String url = "t3://localhost:7001";

String user = null;

String password = null;

Properties properties = null;

try {

properties = new Properties();

properties.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");

properties.put(Context.PROVIDER_URL, url);

if (user != null) {

properties.put(Context.SECURITY_PRINCIPAL, user);

properties.put(Context.SECURITY_CREDENTIALS, password == null ? "" : password);

}

 

 

 

return new javax.naming.InitialContext(properties);

}

catch(Exception e) {

throw e;

}

}

好了,編譯並部署這個SessionBean

 

 

 

新建一個SessionBean的客戶端測試程序:

注意選中Generate logging messages這一項。

Step3中注意選中Create a runtime configuration,這樣可以創建一個運行配置信息。

修改initialize方法以後,變成如下

public void initialize() {

long startTime = 0;

if (logging) {

log("Initializing bean access.");

startTime = System.currentTimeMillis();

}

 

 

 

try {

//get naming context

Context context = getInitialContext();

 

 

 

//look up jndi name

Object ref = context.lookup("SesDDDD");

//look up jndi name and cast to Home interface

sesDDDDHome = (SesDDDDHome) PortableRemoteObject.narrow(ref, SesDDDDHome.class);

if (logging) {

long endTime = System.currentTimeMillis();

log("Succeeded initializing bean access through Home interface.");

log("Execution time: " + (endTime - startTime) + " ms.");

}

//新加的

SesDDDD sesDDDD = sesDDDDHome.create();

System.out.println("@@@@@@@@@@@@"+ sesDDDD.greet());

System.out.println("===========test Successed=====");

 

 

 

}

catch(Exception e) {

if (logging) {

log("Failed initializing bean access.");

}

e.printStackTrace();

}

}

 

 

 

運行測試,將打出如下結果

Succeeded initializing bean access through Home interface.

Execution time: 1922 ms.

##############

宋海龍

##############

===========test Successed=====

         4.              建立一個Servlet

首先要建立一個Web應用,不妨取名爲myservweb

 

 

 

新建一個Servlet

 

 

 

 

 

 

注意在第5步選中Create a runtime configuration

 

 

 

Servlet1.java的源代碼如下:

package cmpseservlet;

 

 

 

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

import java.util.*;

 

 

 

//新加的

import java.rmi.RemoteException;

import javax.rmi.PortableRemoteObject;

import javax.naming.InitialContext;

import javax.naming.*;

import javax.ejb.Handle;

import javax.ejb.EJBMetaData;

import javax.ejb.HomeHandle;

 

 

 

/**

<p>Title: </p>

<p>Description: </p>

<p>Copyright: Copyright (c) 2005</p>

<p>Company: </p>

@author not attributable

@version 1.0

*/

 

 

 

public class Servlet1 extends HttpServlet {

private static final String CONTENT_TYPE = "text/html; charset=GBK";

 

 

 

//新加的

SesDDDD remote;

SesDDDDHome home;

 

 

 

//Initialize global variables

public void init() throws ServletException {

//以下爲新加的

String url = "t3://localhost:7001";

String user = null;

String password = null;

Properties properties = null;

try {

properties = new Properties();

properties.put(Context.INITIAL_CONTEXT_FACTORY,

"weblogic.jndi.WLInitialContextFactory");

properties.put(Context.PROVIDER_URL, url);

if (user != null) {

properties.put(Context.SECURITY_PRINCIPAL, user);

properties.put(Context.SECURITY_CREDENTIALS,

password == null ? "" : password);

}

InitialContext ic = new InitialContext(properties);

Object objref = ic.lookup("SesDDDD");

System.out.println(" == Servlet MySchedule lookup ok");

home = (SesDDDDHome) PortableRemoteObject.narrow(objref, SesDDDDHome.class);

remote = home.create();

System.out.println(" == Servlet home.create ok");

}

catch (Exception e) {

e.printStackTrace();

}

//以上爲新加的

 

 

 

}

//Process the HTTP Get request

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType(CONTENT_TYPE);

PrintWriter out = response.getWriter();

 

 

 

//以下一行爲新加的

String str = (String) remote.greet();

out.println("<html>");

out.println("<head><title>Servlet1</title></head>");

out.println("<body bgcolor=/"#008000/">");

 

 

 

//以下一行爲新加的

out.println(str);

out.println("<p>The servlet has received a GET. This is the reply.</p>");

out.println("</body></html>");

}

//Clean up resources

public void destroy() {

}

}

 

 

 

運行Servlet1顯示頁面如下:

源代碼見:cmpseservlet.rar

發佈了29 篇原創文章 · 獲贊 1 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章