从今天开始,给大家说说Jboss3.0下的EJB的开发,首先给大家说的是一个很简单的SessionBean的开法,在此基础上我会慢慢的说在SessionBean如何连接数据库,如何发电子邮件,如何进行事务处理等等。
一、首先你的保证你的系统能正常的运行起动,对EJB有一定的了解。
二、现在所说的EJB都是标准的EJB没有用到Jboss所特有的特性等等。
1、在E:\我建立了E:\JbossEjbTest\jboss\sessionbean\test目录,在下面我写了以下几个文件,一个是Home接口,一个是Remote接口,一个实现Bean,还有ejb-jar.xml和jboss.xml还有build.bat文件和Client测试文件,还有是Run.bat文件等等。
2、Home接口文件TestSessionHome.java
package jboss.sessionbean.test;
import java.io.Serializable;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBHome;
public interface TestSessionHome extends EJBHome
{
public TestSession create() throws RemoteException, CreateException;
}
3、Remote接口TestSession.java
package jboss.sessionbean.test;
import javax.ejb.EJBObject;
import java.rmi.RemoteException;
public interface TestSession extends EJBObject
{
public String getBeanName() throws RemoteException;
}
4、实现Bean类TestSessionBean.java
package jboss.sessionbean.test;
import java.rmi.RemoteException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
public class TestSessionBean implements SessionBean
{
public String getBeanName()throws RemoteException
{
System.out.println ("Someone called `getBeanName!' Method");
return "This Ejb's Nameis SessionBean Test";
}
public TestSessionBean() {}
public void ejbCreate() {}
public void ejbRemove() {}
public void ejbActivate() {}
public void ejbPassivate() {}
public void setSessionContext(SessionContext sc) {}
}
以上是三个最基本的文件,很简单。但一个最简单的测试算是OK了。
接下来的是两个配置文件
1、ejb-jar.xml配置文件
<?xml version="1.0" encoding="iso8859-1"?>
<ejb-jar>
<enterprise-beans>
<description>JBoss Ejb Test</description>
<display-name>Test</display-name>
<session>
<ejb-name>TestSession</ejb-name>
<home>jboss.sessionbean.test.TestSessionHome</home>
<remote>jboss.sessionbean.test.TestSession</remote>
<ejb-class>jboss.sessionbean.test.TestSessionBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Bean</transaction-type>
</session>
</enterprise-beans>
</ejb-jar>
2、jboss.xml配置文件
<?xml version="1.0" encoding="iso8859-1"?>
<jboss>
<enterprise-beans>
<session>
<ejb-name>TestSession</ejb-name>
<jndi-name>TestSessionHomeJndi</jndi-name>//这里是在客户端调用的JNDI名
</session>
</enterprise-beans>
</jboss>
下面的是一个Build文件,主要是打包生成jar文件。平时我最喜欢用的是ant工具,不过为了很通用而容易使用,所以写了Bat文件的形式build.bat
set JAVA_HOME=e:\jdk1.3.1
set JBOSS_HOME=e:\Jboss3.0_Tomcat4.03
@echo.
@echo ============== Building JbossEjb ============
@echo.
set JDK_CLASSES=%JAVA_HOME%\lib\tools.jar
set CLASSPATH=.;%JDK_CLASSES%;%JBOSS_HOME%\server\default\lib\jboss-j2ee.jar
set PATH=%JAVA_HOME%\bin;%PATH%
set JAVAC=%JAVA_HOME%\bin\javac
mkdir ejbtemp
mkdir ejbtemp\META-INF
%JAVAC% -d ejbtemp *.java
copy META-INF\*.xml ejbtemp\META-INF
cd ejbtemp
jar vcf TestSession.jar jboss/sessionbean/test/*.class META-INF
jar -tvf TestSession.jar
cd ..
@echo on
@echo.
运行这个批处理文件后在E:\JbossEjbTest\jboss\sessionbean\test目录下生成一个ejbtemp目录在下面有一个TestSession.jar文件,把它放在server\default\deploy目录下会自动发布的。
下面的是客户端测试的两个文件,
TestClient.java文件,这是一个应用形式的java文件,在后我会通过jsp,servlet等各种Client端来测试。
import javax.naming.*;
import javax.rmi.PortableRemoteObject;
import jboss.sessionbean.test.*;
import java.util.*;
public class TestClient{
public TestClient(){
}
public static void main(String[] args) {
Hashtable hash=new Hashtable();
hash.put("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
hash.put("java.naming.provider.url","localhost:1099");
try{
InitialContext context = new InitialContext(hash);
Object testObject = context.lookup("TestSessionHomeJndi");
TestSessionHome testSessionHome = (TestSessionHome)PortableRemoteObject.narrow(testObject,TestSessionHome.class);
TestSession testSession = testSessionHome.create();
System.out.println("Ejb Name:"+testSession.getBeanName());
}
catch(Exception e)
{
System.out.println(e.toString());
}
}
}
运行和编译的批处理文件Run.bat文件
set JAVA_HOME=e:\jdk1.3.1
set JBOSS_HOME=e:\Jboss3.0_Tomcat4.03
set Program_HOME=E:\JbossEjbTest\jboss\sessionbean\test
@echo.
@echo ============== Building JbossEjb ============
@echo.
set JDK_CLASSES=%JAVA_HOME%\lib\tools.jar
set CLASSPATH=%JDK_CLASSES%;%Program_HOME%\ejbtemp;%JBOSS_HOME%\client\jbosssx-client.jar;%JBOSS_HOME%\client\jboss-client.jar;%JBOSS_HOME%\client\log4j.jar;%JBOSS_HOME%\server\default\lib\jboss-j2ee.jar;%JBOSS_HOME%\client\jnp-client.jar;%JBOSS_HOME%\client\jnet.jar;%JBOSS_HOME%\client\jboss-common-client.jar;
set PATH=%JAVA_HOME%\bin
set JAVAC=%JAVA_HOME%\bin\javac
set JAVA=%JAVA_HOME%\bin\java
%JAVAC% TestClient.java
set CLASSPATH=%CLASSPATH%;.
%JAVA% TestClient
@echo on
@echo.
以上就是这个基本测试所测试的文件,在你进行测试的时候,你可要修改的就是一些路径如JAVA_HOME;JBOSS_HOME;Program_HOME等等,同时这是一个很简单的测试SessinBean的东东,我会在上面的基础上慢慢的扩大,拓展其很多方面的运用。好了,今天就OK到这里了。
SessionBean连接数据库其实和JSP中基本上是一样的。
一、参考前面的配置库配置,建立一个数据库的连接服务。
我的配置文件如下(Oracle)
<?xml version="1.0" encoding="UTF-8"?>
<server>
<mbean code="org.jboss.resource.connectionmanager.LocalTxConnectionManager" name="jboss.jca:service=LocalTxCM,name=oracleDS">
<depends optional-attribute-name="ManagedConnectionFactoryName">
<!--embedded mbean-->
<mbean code="org.jboss.resource.connectionmanager.RARDeployment" name="jboss.jca:service=LocalTxDS,name=oracleDS">
<attribute name="JndiName">OracleDS</attribute>
<attribute name="ManagedConnectionFactoryProperties">
<properties>
<config-property name="ConnectionURL" type="java.lang.String">jdbc:oracle:thin:@cuipeng:1521:ora8</config-property>
<config-property name="DriverClass" type="java.lang.String">oracle.jdbc.driver.OracleDriver</config-property>
<config-property name="UserName" type="java.lang.String">system</config-property>
<config-property name="Password" type="java.lang.String">manager</config-property>
</properties>
</attribute>
<depends optional-attribute-name="OldRarDeployment">jboss.jca:service=RARDeployment,name=JBoss LocalTransaction JDBC Wrapper</depends>
</mbean>
</depends>
<depends optional-attribute-name="ManagedConnectionPool">
<!--embedded mbean-->
<mbean code="org.jboss.resource.connectionmanager.JBossManagedConnectionPool" name="jboss.jca:service=LocalTxPool,name=oracleDS">
<attribute name="MinSize">0</attribute>
<attribute name="MaxSize">50</attribute>
<attribute name="BlockingTimeoutMillis">5000</attribute>
<attribute name="IdleTimeoutMinutes">15</attribute>
<attribute name="Criteria">ByContainer</attribute>
</mbean>
</depends>
<depends optional-attribute-name="CachedConnectionManager">jboss.jca:service=CachedConnectionManager</depends>
<depends optional-attribute-name="JaasSecurityManagerService">jboss.security:service=JaasSecurityManager</depends>
<attribute name="TransactionManager">java:/TransactionManager</attribute>
<depends>jboss.jca:service=RARDeployer</depends>
</mbean>
</server>
二、在前面的远程接口文件TestSession.java加入下面这样的一个方法,当然名字可以自定哦
public Collection getDBTableName() throws RemoteException;
三、在实现的Bean中TestSessionBean.java加入对接口中的方法的实现。
public Collection getDBTableName() throws RemoteException
{
Vector temp=new Vector();
System.out.println("Jboss SessionBean Connection DB Test");
try{
InitialContext ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:/OracleDS"); //和前面的对应
Connection conn = ds.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM TAB");
while ( rs.next() ) {
temp.addElement(rs.getString("TNAME"));
}
conn.close();
}catch(Exception e){
System.out.println(e);
}
return temp;
}
四、在测试的Client端文件TestClient.java中修改为如下:
import javax.naming.*;
import javax.rmi.PortableRemoteObject;
import jboss.sessionbean.test.*;
import java.util.*;
public class TestClient{
public TestClient(){
}
public static void main(String[] args) {
Hashtable hash=new Hashtable();
hash.put("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
hash.put("java.naming.provider.url","localhost:1099");
try{
InitialContext context = new InitialContext(hash);
Object testObject = context.lookup("TestSessionHomeJndi");
TestSessionHome testSessionHome = (TestSessionHome)PortableRemoteObject.narrow(testObject,TestSessionHome.class);
TestSession testSession = testSessionHome.create();
System.out.println("Ejb Name:"+testSession.getBeanName());
Collection col=testSession.getDBTableName();
Iterator it=col.iterator();
while(it.hasNext()){
String tableName=(String)it.next();
System.out.println(tableName);
}
}
catch(Exception e)
{
System.out.println(e.toString());
}
}
}
其余的文件都不需要修改,先运行build.bat文件,然后将生成的Jar文件发布,然后运行client端测试run.bat
接上面,在SessionBean进行电子邮件的发送!
一、参考前面的用JavaMail发电子邮件的配置,建立一个连接。
我的mail-service.xml文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<server>
<classpath codebase="lib"
archives="mail.jar, activation.jar, mail-plugin.jar"/>
<mbean code="org.jboss.mail.MailService"
name="jboss:service=Mail">
<attribute name="JNDIName">java:/TestJbossMail</attribute>
<attribute name="User">lacklhl</attribute>//用户名
<attribute name="Password">password</attribute>//密码
<attribute name="Configuration">
<configuration>
<property name="mail.smtp.auth" value="true"/>
<property name="mail.store.protocol" value="pop3"/>
<property name="mail.transport.protocol" value="smtp"/>
<property name="mail.user" value="Etre"/>
<property name="mail.pop3.host" value="pop3.21cn.com"/>
<property name="mail.smtp.host" value="smtp.21cn.com"/>
<property name="mail.from" value="lacklhl@21cn.com"/>
<property name="mail.debug" value="false"/>
</configuration>
</attribute>
</mbean>
</server>
用的是21cn的免费的邮箱,不过它是需要验证的
二、前面的远程接口文件TestSession.java加入下面这样的一个方法,当然名字可以自定哦
public String sendMail(String from,String to,String subject,String content)throws RemoteException;
三、在实现的Bean中TestSessionBean.java如下。
package jboss.sessionbean.test;
import java.rmi.RemoteException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.naming.*;
import javax.sql.*;
import java.sql.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class TestSessionBean implements SessionBean
{
InitialContext ctx;
public String getBeanName()throws RemoteException
{
System.out.println ("Someone called `getBeanName!' Method");
return "This Ejb's Nameis SessionBean Test";
}
public Collection getDBTableName() throws RemoteException
{
Vector temp=new Vector();
System.out.println("Jboss SessionBean Connection DB Test");
try{
DataSource ds = (DataSource) ctx.lookup("java:/OracleDS");
Connection conn = ds.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM TAB");
while ( rs.next() ) {
temp.addElement(rs.getString("TNAME"));
}
conn.close();
}catch(Exception e){
System.out.println(e);
}
return temp;
}
public String sendMail(String from,String to,String subject,String content)throws RemoteException
{
String temp;
try{
Session sessions = (Session) ctx.lookup("java:/TestJbossMail");
MimeMessage msg = new MimeMessage(sessions);
msg.setFrom(new InternetAddress(from));
msg.setRecipients(javax.mail.Message.RecipientType.TO,to);
msg.setSubject(subject);
msg.setSentDate(new java.util.Date());
Multipart multipt = new MimeMultipart();
MimeBodyPart msgbody = new MimeBodyPart();
msgbody.setContent(content,"text/plain");
multipt.addBodyPart(msgbody);
msg.setContent(multipt);
Transport.send(msg);
temp="SendMail OK!";
System.out.println("SendMail OK!");
}
catch(Exception e)
{
temp="Error:"+e;
e.printStackTrace();
}
return temp;
}
public TestSessionBean() {
}
public void ejbCreate() {
try{
ctx = new InitialContext();
}catch(Exception e){
System.out.println(e);
}
}
public void ejbRemove() {}
public void ejbActivate() {}
public void ejbPassivate() {}
public void setSessionContext(SessionContext sc) {}
}
四、Build.bat文件改动如下
set JAVA_HOME=e:\jdk1.3.1
set JBOSS_HOME=e:\Jboss3.0_Tomcat4.03
@echo.
@echo ============== Building JbossEjb ============
@echo.
set JDK_CLASSES=%JAVA_HOME%\lib\tools.jar
set CLASSPATH=.;%JDK_CLASSES%;%JBOSS_HOME%\server\default\lib\jboss-j2ee.jar;%JBOSS_HOME%\server\default\lib\mail.jar
set PATH=%JAVA_HOME%\bin;%PATH%
set JAVAC=%JAVA_HOME%\bin\javac
mkdir ejbtemp
mkdir ejbtemp\META-INF
%JAVAC% -d ejbtemp TestSession*.java
copy *.xml ejbtemp\META-INF
cd ejbtemp
jar vcf TestSession.jar jboss/sessionbean/test/*.class META-INF
jar -tvf TestSession.jar
cd ..
@echo on
@echo.
五、在测试的Client端文件TestClient.java中修改为如下:
import javax.naming.*;
import javax.rmi.PortableRemoteObject;
import jboss.sessionbean.test.*;
import java.util.*;
public class TestClient{
public TestClient(){
}
public static void main(String[] args) {
Hashtable hash=new Hashtable();
hash.put("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
hash.put("java.naming.provider.url","localhost:1099");
try{
InitialContext context = new InitialContext(hash);
Object testObject = context.lookup("TestSessionHomeJndi");
TestSessionHome testSessionHome = (TestSessionHome)PortableRemoteObject.narrow(testObject,TestSessionHome.class);
TestSession testSession = testSessionHome.create();
//Test Method
System.out.println("Ejb Name:"+testSession.getBeanName());
//Test DB
Collection col=testSession.getDBTableName();
Iterator it=col.iterator();
while(it.hasNext()){
String tableName=(String)it.next();
System.out.println(tableName);
}
//Test Mail
String temp=testSession.sendMail("lacklhl@21cn.com","lacklhl@21cn.com","Test SessionBean Mail","Test SessionBean Mail");
System.out.println(temp);
}
catch(Exception e)
{
System.out.println(e.toString());
}
}
}