Jboss 3.2 EJB Examples

Using separate tomcat 4 & databases like hypersonic, Oracle8i and MySql In this 6 part article,

Jboss 3.2 EJB Examples

Jboss 3.2 EJB Examples 

     

Using separate tomcat 4 & databases like hypersonic, Oracle8i and MySql 

In this 6 part article, the author explains the method of developing various types of Enterprise Java Beans, deploying them in JBoss3.2,and accessing them using independent Tomcat4.

Connecting to Hypersonic database,or Oracle8i or MySql database also is covered, as may be required by different customers

Part 1

Stateless session bean jboss 3.2 & accessing through servlet in tomcat4

Nowadays, a lot of companies are recruiting J2EE programmers.Most of the advertisements ask for persons with hands-on experience in J2EE servers like BEA- Weblogic,IBM- Websphere and also the Open-source & free Jboss.

Jboss3.2 is favoured by many medium-level companies as it is high-quality and free. I recently attended an interview and I was asked to actually demonstrate how to connect to MySql from Jboss3.2. We are familiar with LAMP(Linux/Apache/MySql/PHP).( There was a nice tutorial on LAMP by P.C.Rathod in DeveloperIQ (April-2003 -p76 to 95 ). 

The software in this group is free and open-source. We can now add Jboss3.2 and Tomcat also to the list and thus we can use servlet/jsp in Tomcat and connect to EJB (all types) which are deployed in JBoss3.2! Add to that the free Database in JBoss3.2 (ie)Hypersonic database, which also can be used if so desired instead of MySql. and it becomes an excellent combination from the view of economy and performance!

No wonder then, that companies are gradually beginning to tap these advantages of completely open-source and free software!

However, while MySql has a classic documentation and also a number of published books and free ebooks, the documentation available for Jboss 3.2 is rather scanty and difficult to follow , as it straight away begins with JMX!

There have been a series of tutorials on J2EE in DeveloperIQ , from Oct-2003 issue, onwards, written by RS.Ramaswamy.The author was dealing mainly with Weblogic server.However, in JAN-2004 issue, he gave a brief tutorial on practical steps for running a stateless EJB in Jboss3.2 in console-mode..

While, the EJB tutorials gave examples of accessing the EJB using servlets through Tomcat for all the Weblogic examples, there was no such servlet-client example for Jboss3.2. 

That was because,while EJBservers like WebLogic and WebSphere do not come bundled with Tomcat server,Jboss3.2 has built-in Tomcat. There are some problems in running Tomcat as a separate application rather than using the Tomcat which comes bundled with Jboss3.2. .When we attempt to start Tomcat4.1 server separately while JBoss is running , it throws exception that port number is already in use, because the built-in Tomcat is already running.Therefore, we must disable the built-in Tomcat first. That is the crux of the problem! and this prompted me to explore the topic and solve the problem.This tutorial is my attempt to fill up the gaps,because only then we can really tap the power of JBoss3.2.Unless, we are able to access an ejbean by using servlet/jsp, it is not of much use.

When we want to access an Ejbean, deployed in Jboss3.2,through a servlet. ,there are a number of variations possible. (ie) we can use the Tomcat which comes integrated with Jboss3.2. or we can use a separate Tomcat server. The Jboss people recommend the earlier approach for, they say, performance will be better. However, for uniform approach, whatever be the J2EE server ( whether WebLogic or WebSphere or Jboss) , it is better to use an external Tomcat webserver for deploying the servlet/jsp, and accesss the EJB from there.

In this article, we are going to see see how all the four types of EJB,(ie) stateless, stateful, cmp and bmp , deployed in JBoss3.2.2 can be accessed by a servlet client deployed in independent Tomcat4 web server.

Writing EJB Code is not very difficult and mostly it follows the same pattern for all applications. But deployment of the EJBean in application server has to be done carefully, because,the deployment process in one server is different from the other.( the procedure in WebLogic may differ from Jboss).Even in the same server, the procedure may differ from one version to another. (say) WebLogic 5.1 procedure may differ from that for WebLogic7 or 8.

Since weblogic7/8 provides clear documentation and examples, it may not be very difficult to develop EJB programs in that server.But in JBoss3.2.2, documentation is not clear. Even though JBoss-3.2.2 (being open and free) is recognized and sought after in the Enterprise level, books are not readily available in the market, while there are a number of books on WebLogic/WebSphere servers.

I felt that it will be useful , if I could create very simple and clear examples for all the various possibilitees , in Jboss3.2. and share it with our student readers and hence these lessons.

It is always a good practice to develop J2EE application in separate layers.That is why we deploy the ejbean in Jboss and call it from a servlet deployed in an independent Tomcat server ( as we have been doing in our lessons in weblogic so far in the earlier tutorials).

The procedure to disable the built-in Tomcat in JBoss3.2 is as follows: cd to: D:\jboss-3.2.2\server\default\deploy\ Jbossweb-tomcat41.sar\META-INF

In the META-INF folder, we?ll find the jboss-service.xml file. In this file remove all the contents between <server> tag & </server> tag.When this is done, the xml file will contain only empty <server> tag section. (But don?t delete the file)

Now open another DOS window and start the JBoss server. Jboss server alone will run. It won?t start the built-in Tomcat server. So we are now able to start the tomcat server separately. There won?t be any port clash exception now. This is an important tip , developed by trial and error.

Having settled this problem for good, we now proceed to develop examples for all the types of EJB such as Stateless, Stateful, CMP & then BMP.In all the cases, we will use, servlet-client only.and see how to use them from JBoss server.

a) Stateless Session Bean:

For the sake of clarity and continuity, I am using the same example as given by RS.Ramaswamy in his writeup on JBoss3.2 in Jan-2004 issue of DeveloperIQ(page-108 ). So , readers already familiar with the earlier tutorial may find this repetetive to a certain extent.This is being risked as it will make this tutorial self-contained .So, kindly read on.

Let us create our working folder as: d:\greeter set path & classpath as given below,for this window.

d:\greeter>

set path= c:\windows\command; d:\jdk1.4\bin;

d:\greeter> set classpath= d:\greeter;

d:\jboss-3.2.2\client\log4j.jar;

d:\jboss-3.2.2\client\

jboss-system-client.jar;

d:\jboss-3.2.2\client\

jboss-common-client.jar;

d:\jboss-3.2.2\client\

jboss-client.jar;

d:\jboss-3.2.2\client\

jbosssx-client.jar;

d:\jboss-3.2.2\client\

jboss-j2ee.jar;

d:\jboss-3.2.2\client\

jnp-client.jar;

d:\jboss-3.2.2\client\

jboss-transaction-client.jar;

d:\jboss-3.2.23.2.2\server\

default\lib\javax.servlet.jar;

( Give the classpath in a single line. Specify the jar files continuously.)

create and compile

greetRemote.java,

greetHome.java,

greetBean.java

in d:\greeter folder.( working folder). 

// d:\greeter\greetRemote.java
import javax.ejb.*;
import java.rmi.*;

    public interface greetRemote extends EJBObject{
	public String greetme(String s) throws RemoteException;
} 

// d:\greeter\greetHome.java
import javax.ejb.*;
import java.rmi.*;
public interface greetHome extends EJBHome{
	public greetRemote create() throws 
		RemoteException,CreateException;
}
// d:\greeter\greetBean.java
import javax.ejb.*;
import java.rmi.*;
import javax.naming.*;

public class greetBean implements
SessionBean
	{
   public String greetme(String s)
	throws RemoteException
    {
	return "How are you?......."+s;
     }
	public void ejbCreate(){}
	public void ejbRemove(){}
	public void ejbActivate(){}
	public void ejbPassivate(){}
	public void setSessionContext
	(SessionContext sc ) {}
}

Compile these files.

d:\greeter> javac *.java

create a subfolder META-INF under our working folder.Create ejb-jar.xml, jboss.xml there ( These two files are essential).

// d:\greeter\META-INF\ejb-jar.xml

<?xml version="1.0"?>
<!DOCTYPE ejb-jar PUBLIC"-//Sun Microsystems, 
Inc.//DTD Enterprise JavaBeans 2.0//EN""http://java.sun.com/dtd/ejb-jar_2_0.dtd">
<ejb-jar>
	<enterprise-beans>]
	   <session>
		<ejb-name>greetBean</ejb-name>
		<home>greetHome</home> 
		<remote>greetRemote</remote>
		<ejb-class>greetBean</ejb-class>
		<session-type>Stateless</session-type>
		<transaction-type>Container </transaction-type>
	   </session>
	</enterprise-beans>
</ejb-jar>


Session type must be ?Stateless? and transaction-type must be Container for all stateless session applications.

// d:\greeter\META-INF\jboss.xml
<?xml version='1.0' ?>
<!DOCTYPE jboss PUBLIC"-//JBoss//DTD JBOSS 3.2//EN" 
"http://www.jboss.org/j2ee/dtd/jboss_3_2.dtd">
	<jboss>
	<enterprise-beans>
		<entity>
			<ejb-name>greetBean</ejb-name>
			<jndi-name>greetJndi</jndi-name>
		</entity>
	</enterprise-beans>
</jboss>

Create a jar file as given below.

d:\greeter>

jar cvf greet.jar *.class META-INF\*.xml

The next step is to deploy the ejb jar file to JBoss server.

d:\greeter>

copy greet.jar 

d:\jboss-3.2.2\server\default\deploy

we can deploy the jar file either before starting JBoss server or after it starts running. If the message ?Deployed package?? for greet.jar is displayed in the JBoss server window, then it is deployed successfully. If it shows any exception, then verify xml files. Upto this, EJB part is over. Next comes the client part create and complie greetServlet.java for accessing ejb.

// d:\greeter\greetServlet.java

// d:\greeter\greetServlet.html
import java.net.*;
import javax.ejb.*;
import javax.rmi.*;
import java.rmi.*;
import javax.naming.*;
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class greetServlet extends HttpServlet
{
public void doPost
(HttpServletRequest req, HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
try
{
Properties props=new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
props.put(Context.PROVIDER_URL, "localhost:1099");
props.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
System.out.println("Properties ok");
Context ctx=new InitialContext(props);
System.out.println("context ok");
greetHome home = (greetHome)
ctx.lookup("greetJndi");
System.out.println("home ok");
greetRemote remote=home.create();
System.out.println("remote ok");
String a = req.getParameter("text1");
String s = remote.greetme(a);
System.out.println(s);
out.println(s);
}
catch(Exception e)
{System.out.println(""+e);}
}
}

 


// d:\greeter\greetServlet.html
<html>
<body>
<form method=post action= "http://localhost:8080
/greeterapp/servlet/ greetServlet"> 
<input type=text name="text1">
<input type=submit>
</form>
</body>
</html>

Compile the servlet: d:\greeter> javac greetServlet.java (as javax.servlet.jar is in classpath of this window, we will be able to compile the servlet without problem.).

We follow the procedure outlined below to deploy the servlet in tomcat4.1. We have installed tomcat4 in D: drive. First of all we create a folder named 'greeterapp' under webapps directory of Tomcat4. d:\tomcat4.1\webapps>md greeterapp cd to that folder.

..\greeterapp>md WEB-INF

Create two sub-folders under WEB-INF 

..\WEB-INF>md classes

 ..\WEB-INF>md lib

copy d:\greeter\greeterServlet.html to: d:\tomcat4.1\webapps\greeterapp

copy d:\greeter\greeterServlet.class to: d:\tomcat4.1\webapps\greeterapp WEB-INF\classes

copy d:\greeter\ greet.jar to: d:\tomcat4.1\webapps\greeterapp\WEB-INF\lib

Also copy all JBoss jar files, which we?ve mentioned in the classpath of our project folder (ie) d:\greeter , to : d:\tomcat4.1\webapps\greeterapp\WEB-INF\lib

Create web.xml file in: d:\tomcat4.1\webapps\greeterapp\WEB-INF 

d:\tomcat4.1\webapps\greeterapp\WEB-INF\web.xml

<?xml version="1.0" encoding="ISO-8859-1"?> 
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" 
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<servlet>
	<servlet-name>greetServlet </servlet-name>
	<servlet-class>greetServlet </servlet-class>
</servlet>
<servlet-mapping>
	<servlet-name>greetServlet</servlet-name>
	<url-pattern>/servlet/greetServlet
</url-pattern>
</servlet-mapping>
</web-app>

The servlets deployed in Tomcat4.1 must have a reference in the web.xml file. If it is not mentioned, then server will throw exception that it couldn?t find the class

Start Jboss3.2 server in another dos window: d:\jboss-3.2.2\bin> set JAVA HOME= d:\jdk1.4 

d:\jboss-3.2.2\bin> run

This command will start the jboss server.

Start tomcat server

d:\tomcat4.1\bin>

set JAVA_HOME= d:\jdk1.4

d:\tomcat4.1\bin> startup This command will start tomcat server.

Open IE and type url as "http://localhost:8080/greeterapp/greetServlet.html' (Refer to page 102 in the March issue of DeveloperIQ) Type 'tom' in the text box and submit it.We?ll get the result as 'How are you.........tom'  Thus, we have shown how to develop a stateless session bean , deploy it in Jboss3.2 and invoke it through a servlet deployed in a separate Tomcat4.1 server. In the next part, we will develop a stateful ejb and give a similar demo.

Part-2

Stateful Session-Bean in Jboss3.2 accessed by servlet in tomcat4 

In this lesson, the author shows how to develop a typical stateful session bean , deploy it in JBoss3.2 and access it by a session-tracking servlet in separate Tomcat4 webserver. In an earlier example of this tutorial series, (by RS.Ramaswamy) though a stateful bean was developed , it had a console mode client only.

Actually, a console-mode client will retain state of the vector but when we convert this into a web-client, state will not be maintained at the webserver side, as HTTP is a stateless protocol. So, for a stateful ejb with a servlet/jsp client, we should make some arrangement for session-tracking in webserver. This has not been covered in the earlier tutorials. Evidently, this is most important point in practical work and so readers are requested to note this carefully.

Our working folder is d:\carter

set path and classpath as we did in part-1 of this tutorial on stateless bean. (when setting classpath, we should always begin with our working folder! in our case now, it is d:\carter; )

We create cartRemote.java, cartHome.java and cartBean.java in our working folder (The source-code for these three are the same as given earlier in Nov-2004 issue of DeveloperIQ page-102 . It is being repeated here for readers who missed that issue and also to make this tutorial self-contained. )

// d:\carter\cartRemote.java
import javax.ejb.*;
import java.rmi.*;
import java.util.*;
public interface cartRemote
extends EJBObject
{
public void addbooks(String s) 
throws RemoteException;
public Vector getbooks()
throws RemoteException;
}

 

// d:\carter\cartHome.java
import javax.ejb.*;
import java.rmi.*;
public interface cartHome extends EJBHome
{
public cartRemote create(String s)
throws RemoteException,CreateException
}

 


Note carefully that create method is having String parameter, since a new bag is created for each user. For stateless bean, it is empty.


// d:\carter\ cartBean.java
import javax.ejb.*;
import java.rmi.*;
import javax.naming.*;
import java.util.*;
public class cartBean implements
SessionBean
{
Vector vector1;
public void addbooks(String s)
throws RemoteException
{
vector1.addElement(s);
}
public Vector getbooks()
throws RemoteException
{
return vector1;
}
public void ejbCreate(String s)
{
vector1=new Vector();
}
public void ejbRemove() {}
public void ejbActivate() {}
public void ejbPassivate() {}
public void setSessionContext
( SessionContext sc) {}
}

 

We compile these three files now.

d:\carter> javac *.java

create a subfolder META-INF under our working folder (ie) d:\carter

create ejb-jar.xml, jboss.xml ( These two files are essential ).

ejb-jar.xml

<?xml version="1.0"?>


<!DOCTYPE ejb-jar PUBLIC

"-//Sun Microsystems, Inc.//DTD Enterprise j 2.0//EN"

"http://java.sun.com/dtd/ejb-jar_2_0.dtd">


<ejb-jar>

<enterprise-beans>

<session>

<ejb-name>cartBean</ejb-name>

<home>cartHome</home>

<remote>cartRemote</remote>

<ejb-class>cartBean</ejb-class>

<session-type>Stateful</session-type>

<transaction-type>

Container </transaction-type>

</session>

</enterprise-beans>

</ejb-jar>


Session type must be ?Stateful? and transaction type must be ?Container? for all Stateful applications.

jboss.xml

<?xml version='1.0' ?>

<!DOCTYPE jboss PUBLIC

"-//JBoss//DTD JBOSS 3.2//EN"

"http://www.jboss.org/j2ee/dtd/jboss_3_2.dtd">


<jboss>

<enterprise-beans>

<entity>

<ejb-name>cartBean</ejb-name>

<jndi-name>cartJndi</jndi-name>

</entity>

</enterprise-beans>

</jboss>


7) create a jar file as given below.

d:\carter>

jar cvf cart.jar *.class META-INF\*.xml


8) For deploying ejb in jboss,

copy cart.jar from d:\carter to:

d:\jboss- 3.2.2 \server\default\deploy


9) create and complie cartServlet.java for accessing ejb.

// d:\carter\cartServlet.java

import javax.ejb.*;
import java.rmi.*;
import javax.rmi.*;
import javax.naming.*;
import java.util.*;
import cartremote;
import carthome;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class cartServlet extends HttpServlet
{
carthome home;
public void init(ServletConfig config)
throws ServletException
{
super.init(config);
try
{
Properties props=new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, 
"org.jnp.interfaces.NamingContextFactory");
props.put(Context.PROVIDER_URL, "localhost:1099");
props.put(Context.URL_PKG_PREFIXES, 
"org.jboss.naming:org.jnp.interfaces");
System.out.println("Properties ok");
Context ctx=new InitialContext(props);
System.out.println("context ok");
home = (carthome)ctx.lookup("cartJndi");
System.out.println("Home ready");
}catch(Exception e1)
{System.out.println(""+e1);}

}

public void doPost
(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//------------------------------------------
String s1 = request.getParameter("combo1); 
HttpSession bag=request.getSession(true);
String ids = bag.getId();// session id 
try
{
cartremote remote =
(cartremote)bag.getValue(ids); 
if(remote==null)
{
remote=home.create(ids);
bag.putValue(ids,remote);
}
remote.addbook(s1);
Vector vector1 = remote.getbooks();
System.out.println(vector1.toString());
out.println(ids);
out.println("<br>");
out.println(vector1.toString()); 

} catch(Exception e1)
{ System.out.println(" " + e1); }
}

}

 

// d:\carter\cartServlet.htm
<html>
<body>
<form method=post 
action="http://localhost:8080/carterapp/servlet/cartServlet"> 
<select name="combo1">
<option value="JAVA NOW">JAVANOW
<option value="VISUALBASIC6">VISUALBASIC
<option value="LET US C">LET US C
<option value="ORACLE8i">ORACLE8i
</select>
<input type=submit>
</form>
</body>
</html>


compile cartServlet.java d:\carter> javac cartServlet.java

We follow the procedure outlined below to deploy the servlet in tomcat4.1.

We have installed tomcat4 in D: drive.

Begin by creating a new folder under webapps folder of Tomcat, as shown below.

d:\tomcat4.1\webapps>md carterapp

As before, create WEB-INF folder.

..\carterapp>md WEB-INF

Create two sub-folders under WEB-INF

..\WEB-INF>md classes

..\WEB-INF>md lib

copy d:\carter\cartServlet.htm to:

d:\tomcat4.1\webapps\carterapp

copy d:\carter\cartServlet.class to:

d:\tomcat4.1\webapps\carterapp\ 

WEB-INF\classes

copy d:\carter\ cart.jar to: d:\tomcat4.1\webapps\carterapp\WEB-INF\lib

Also copy all JBoss jar files, which we?ve mentioned in the classpath of our project folder (ie) d:\carter , to : d:\tomcat4.1\webapps\carterapp\  WEB-INF\lib

15) create web.xml under WEB-INF folder

( This file is essential for any web application) d:\carter\WEB-INF> edit web.xml

web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<servlet>

<servlet-name>cartServlet</servlet-name>

<servlet-class>cartServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>cartServlet</servlet-name>

<url-pattern>

/servlet/cartServlet

</url-pattern>

</servlet-mapping>

</web-app>

Open another dos window and start Jboss server d:\jboss-3.2.2\bin> set JAVA_HOME=d:\jdk1.4 d:\jboss-3.2.2\bin> run

This command will start the jboss server.

Start tomcat server

d:\tomcat4.1\bin> set JAVA_HOME=d:\jdk1.4 d:\tomcat4.1\bin> startup

This command will start tomcat server.

Open IE and type url as 'http://localhost:8080/carterapp/cartServlet.htm' Select any book from the combo in the form,and add to the bag by confirming by submit button. We find that the books are added to the bag and displayed in the browser .

That completes the second part of this tutorial on JBoss3.2. We now take up CMP entity bean in part-3 of this tutorial which follows.

Part-3

CMP Entity-Bean in Jbss 3.2

Using built-in hypersonic database and separate tomcat4

In this lesson, the author gives demo for developing a CMP Entity bean, deploying it in JBoss3.2 and accessing it from a servlet deployed in a sepatrate Tomcat4 server. We are using Hypersonic database , which comes bundled with JBoss3.2! This is followed by Oracle database demo.& MySql database demo in Part-4.

The theory for Entity beans has already been covered in December-2003 issue of DeveloperIQ Since Hypersonic is the built-in and default database for Jboss, we don?t need to worry about database setup. There are two xml files, which deal with database configurations. One is standardjbosscmp-jdbc.xml under ?\ server \ default \ conf? folder and other one is hsqldb-ds.xml under ?\ server \ default \ deploy ? folder.

As far as this example is concerned, we use Hypersonic database only. So we don?t make any changes in the above mentioned files. In the next part, we?ll see how to connect Jboss with other databases.( such as Oracle8i & MySql).

Now we are going to create a table of three columns ie. key, name, place which are all string datatype in Hypersonic database and do all DML Operations.We are following this simple table so as to maintain continuity with the earlier lessons on CMP & BMP.

Let us create our own working folder as d:\cmpdemo set path and classpath as given below.

d:\cmpdemo>

set path=c:\windows\command; d:\jdk1.4\bin;

d:\cmpdemo> set classpath= d:\cmpdemo;

d:\jboss-3.2.2\client\log4j.jar;

d:\jboss-3.2.2\client\jboss-system-client.jar;

d:\jboss-3.2.2\client\jboss-common-client.jar;

d:\jboss-3.2.2\client\jboss-client.jar;

d:\jboss-3.2.2\client\jbosssx-client.jar;

d:\jboss-3.2.2\client\jboss-j2ee.jar;

d:\jboss-3.2.2\client\jnp-client.jar;

d:\jboss-3.2.2\client\

jboss-transaction-client.jar;

d:\jboss-3.2.2\server\default\

lib\javax.servlet.jar;

( Give the classpath in a single line. Specify the jar files continuously.)

create and compile customerRemote.java, 

customerHome.java, customerBean.java

customerRemote.java

import javax.ejb.*;
import java.rmi.*;

public interface customerRemote
extends EJBObject
{
public String getKey() throws
RemoteException;
public String getName() throws 
RemoteException;
public void setName (String s) throws 
RemoteException;
public String getPlace() throws 
RemoteException;
public void setPlace(String s) throws 
RemoteException;
}

 


There should not be any set method for primary key field. So setKey() method is not given in the remote interface. But there must be set and get methods declared for each field.

customerHome.java


import javax.ejb.*;
import java.rmi.*;

public interface customerHome
extends EJBHome
{
public customerRemote create
(String a,String b, String c)
throws RemoteException, CreateException;

public customerRemote 
findByPrimaryKey (String a)
throws RemoteException, FinderException; 
}

 


Here one more pre-defined method called findByPrimaryKey method is added which we?ve not seen in session beans. This method is must for all CMP applications and it is used to search the record by finding the primary key. Primary key is a unique identification of the record. There may be other user-defined finder methods also included in the file.

customerBean.java

import javax.ejb.*;
import java.rmi.*;

public abstract class
customerBean implements EntityBean
{ 
public abstract String getKey();
public abstract void setKey(String s);
public abstract String getName();
public abstract String getPlace();
public abstract void setName(String b);
public abstract void setPlace(String c);

public String ejbCreate
(String a,String b, String c)
throws CreateException
{
setKey(a);
setName(b);
setPlace(c);

return null; // correct!
}

public void ejbPostCreate 
(String a,String b,String c) 
throws CreateException {}

public void ejbActivate() {}
public void ejbPassivate() {}
public void ejbRemove() {}
public void ejbLoad() {}
public void ejbStore() {}
public void setEntityContext
(EntityContext ec) {}
public void unsetEntityContext() {}
}

 

Carfully note the Bean file. It should be defined as abstract and all set and get functions of the field also must be abstract. Here set method for primary key is included so that while updating / inserting records, the container calls this method.)

compile customerRemote.java, customerHome.java, customerBean.java

d:\cmpdemo> javac *.java

create a subfolder META-INF under our

working folder.

create ejb-jar.xml, jboss.xml

In addition, CMP needs one more xml called

jbosscmp-jdbc.xml.

ejb-jar.xml

<?xml version="1.0"?> 

<!DOCTYPE ejb-jar PUBLIC

'-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN'

'http://java.sun.com/dtd/ejb-jar_2_0.dtd'>


<ejb-jar>

<enterprise-beans>

<entity>

<ejb-name>customerBean</ejb-name>

<home>customerHome</home>

<remote>customerRemote</remote>

<ejb-class>customerBean</ejb-class>

<persistence-type>

Container

</persistence-type>

<prim-key-class>

java.lang.String

</prim-key-class>

<reentrant>False</reentrant>

<cmp-version>2.x</cmp-version>

<abstract-schema-name>

table1

</abstract-schema-name>

<cmp-field>

<field-name>key</field-name>

</cmp-field>



<cmp-field>

<field-name>name</field-name>

</cmp-field>



<cmp-field>

<field-name>place</field-name>

</cmp-field>



<primkey-field>key</primkey-field>

</entity>

</enterprise-beans> 

</ejb-jar>

This ejb-jar.xml file is something different from the one which we?ve mentioned in Stateless and Stateful Session beans. Here abstract schema name, cmp field definition ,primary key details etc are included. These details are very important since container is going to manage the table.

jboss.xml

<?xml version="1.0" encoding="UTF-8"?>

<jboss> 

<enterprise-beans>

<entity>

<ejb-name>customerBean</ejb-name>

<jndi-name>customerJndi</jndi-name>

</entity>

</enterprise-beans> 

</jboss>

jbosscmp-jdbc.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE jbosscmp-jdbc>

<jbosscmp-jdbc>


<defaults>

<datasource>java:/DefaultDS</datasource>

<datasource-mapping>

Hypersonic SQL

</datasource-mapping>

<create-table>true</create-table>

<remove-table>false</remove-table>

<pk-constraint>true</pk-constraint>

<preferred-relation-mapping>

foreign-key

</preferred-relation-mapping>

</defaults>

<enterprise-beans>

<entity>

<ejb-name>customerBean</ejb-name>

<table-name>table1</table-name>

<cmp-field>

<field-name>key</field-name>

<column-name>key</column-name>

</cmp-field>

<cmp-field>

<field-name>name</field-name>

<column-name>name</column-name>

</cmp-field>

<cmp-field>

<field-name>place</field-name>

<column-name>place</column-name>

</cmp-field>

</entity>

</enterprise-beans>


</jbosscmp-jdbc>

jboss.xml file is the usual one.

In the jbosscmp-jdbc.xml file, we are connecting our application to the database by giving datasource name and its mapping. If create-table value is true, then container will create a new table with a name given in the table-name tag. If it is false, it uses the table given in the table-name tag. Then the column name declared in the table is matched over field name used by the container in <cmp-field> tag.

create a jar file as given below.

d:\cmpdemo>

jar cvf customer.jar *.class META-INF\*.xml

For deploying ejb in jboss,

d:\cmpdemo> copy customer.jar d:\jboss-3.2.2\server\default\deploy

create and complie customerServlet.java for accessing ejb.
0

//d:\cmpdemo\customerServlet.java
import customerRemote;
import customerHome; 
import javax.ejb.*;
import java.rmi.*;
import javax.rmi.*;
import javax.naming.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class customerservlet extends HttpServlet{
customerHome home;
public void init(ServletConfig config) throws ServletException {
super.init(config); 
try{
System.out.println("please wait!");
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.
jnp.interfaces.NamingContextFactory");
props.put(Context.PROVIDER_URL,"localhost:1099");
props.put(Context.URL_PKG_PREFIXES, "org.jboss.
naming:org.jnp.interfaces");
System.out.println("Properties ok"); 
Context ctx = new InitialContext(p);
home = (customerHome) ctx.lookup("customerJndi");
System.out.println("home located");
}catch(Exception e1){
System.out.println(" "+e1);
}
}// init over

public void doPost(HttpServletRequest request, HttpServletResponse 
response) throws ServletException, IOException{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
try{ 
String a = request.getParameter("text1"); // key
String b = request.getParameter("text2"); // name
String c = request.getParameter("text3"); //place
String d = request.getParameter("combo1");// operation
String e = request.getParameter("combo2"); // name/place
String s = request.getParameter("text4");// criterion
if(d.equals("add")){ 
home.create(a,b,c); 
out.println("record created"); 
}
if(d.equals("find")){ 
customerRemote remote= home.findByPrimaryKey(a);
out.println("name:..."+"\t"+remote.getName());
out.println("place:..."+""+remote.getPlace()); 
} 
if(d.equals("update")){
customerRemote remote = home.findByPrimaryKey(a);
if(e.equals("name")){
remote.setName(s);
String n = remote.getName();
out.println("Name updated");
out.println(n);
}
if(e.equals("place")){
remote.setPlace(s);
String n1=remote.getPlace();
out.println("place updated");
out.println(n1);
}
}
if(d.equals("delete")){
customerRemote remote = home.findByPrimaryKey(a);
remote.remove();
out.println("record removed"); 
} 
}catch(Exception e2){
System.out.println(""+e2);
}
}
}

customerServlet.htm

<html>

<body>

<form method=post action="http://localhost:8080/cmpapp/

servlet/customerServlet">

Key <input type=text name="text1"><br>

Name <input type=text name="text2"><br>

Place <input type=text name="text3"> <br>

<select name=combo1>

<option value="add"> add

<option value="find"> find

<option value="update"> update

<option value="delete"> delete

</select><br>

What do you want to change?

<select name=combo2>

<option value="name"> Name

<option value="place"> Place

</select> <br>

By what value <input type=text name="text4"> <br>

<input type=submit>

</form>

</body>

</html>

complie customerServlet.java

d:\cmpdemo> javac customerServlet.java

) We follow the procedure outlined below to deploy the servlet in tomcat4.1.We have installed tomcat4 in D: drive. d:\tomcat4.1\webapps>md cmpapp

..\cmpapp>md WEB-INF

Create two sub-folders under WEB-INF

..\WEB-INF>md classes

..\WEB-INF>md lib

copy d:\cmpdemo\customerServlet.htm to: d:\tomcat4.1\webapps\cmpapp

copy d:\cmpdemo\customerServlet.class to: d:\tomcat4.1\webapps\cmpapp\WEB-INF\classes

copy d:\cmpdemo\ customer.jar to: d:\tomcat4.1\webapps\cmpapp\ WEB-INF\lib

Also copy all JBoss jar files, which we?ve mentioned in the classpath of our project folder (ie) d:\cmpdemo , to : d:\tomcat4.1\webapps\cmpapp\ WEB-INF\lib create web.xml under WEB-INF folder ( This file is essential for any web application) d:\cmpdemo\WEB-INF> edit web.xml

Web.xml


<?xml version="1.0" encoding="ISO-8859-1"?>


<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<servlet>

<servlet-name>customerServlet</servlet-name>

<servlet-class>customerServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>customerServlet </servlet-name>

<url-pattern>

/servlet/customerServlet

</url-pattern>

</servlet-mapping>

</web-app>

Open another dos window and start Jboss server d:\jboss-3.2.2\bin> set JAVA_HOME=d:\jdk1.4 d:\jboss-3.2.2\bin> run

This command will start the jboss server. Open another dos window and start Tomcat server d:\tomcat4.1\bin>set JAVA_HOME=d:\jdk1.4 d:\tomcat4.1\bin> startup

This command will start the tomcat server. Open IE and type url as 'http://localhost:8080/cmpapp/cartServlet.html' Enter '100' as key value, 'sam' as name value, 'Mumbai' as place value, Choose 'add' in combo1 and submit it.

New record will be created in the Hypersonic database. Checkup by giving key value as 100 , opeartion as 'find'.For doing other manipulations, enter the values accordingly.and experiment.

In part4 of this tutorial , we will use Oracle8i database.

Part-4

CMP Entity-Bean in Jboss 3.2 Server using Oracle8i Database & Tomcat4

In this lesson, the author, shows how we can use Oracle8i and MySql database along with JBoss3.2, avoiding Hypersonic database, bundled with JBoss3.2.

Instead of using Hypersonic,which is the built-in database in JBoss3.2, we can choose our own database. Some companies already have such an Oracle8i database and would like to use it along with JBoss3.2.

Remote, Home and Bean codes are same as given in the previous example. We?ve to make changes in the jbosscmp-jdbc.xml file of our application and the two database configuration xml files of the server. The exact procedure is given below.

cd to: D:\jboss-3.2.2\server\default\deploy edit hsqldb-ds.xml in this folder as follows: 
1

<jndi-name>OracleDS</jndi-name> <connection-url>

jdbc:oracle:thin:@localhost:1521:DEVA 

</connection-url>

<driver-class>

oracle.jdbc.driver.OracleDriver

</driver-class>

<user-name>scott</user-name>

<password>tiger</password>

?DEVA? is the name of the Oracle server that I gave when I installed Oracle8i in my system. In your machine, change appropriately. Don?t alter anything other than this.

Now, cd to: d:\jboss-3.2.2\server\default\conf>

edit standardjbosscmp-jdbc.xml file

Give the values as follows:

<datasource>java:/OracleDS</datasource>

<datasource-mapping>

Oracle8

</datasource-mapping>

Type mapping for Oracle8 is already defined  in the file. Leave the remaining contents of file as it is.

Then edit jbosscmp-jdbc.xml file of our application.

<datasource>java:/OracleDS</datasource>

<datasource-mapping>

Oracle8

</datasource-mapping>

Remaining things are left as they are.

Copy classes111.zip file to the Jboss server

lib directory and also to ?\WEB-INF\lib? folder of our application. 

(111..one hundred and eleven!) d:\jboss-3.2.2\server\default\lib> 2

copy d:\oracle\ora81\lib\classes111.zip if we forget to do this, Jboss won?t connect to oracle. It won?t find the url and driver class.

After making all these alteration, create a ejb

Remote, Home and Bean files as given CMP with Hypersonic database.After compiling all these files, create jar file as usual and deploy it in Jboss.During deployment, Jboss checks the database configuration details and the one used in our application. If it coincides, then ejb jar will be successfully deployed. Otherwise it throws exception. Now we can execute EJB by writing servlet program which is deployed in tomcat4.1.The servlet program is same as mentioned in CMP-Hypersonic part.

CMP - MySQL 3.23- Jboss-3.2.2 - Tomcat4.1

Today, the trend is in the use of open source. MySQL3.2 is open and free software. It is very fast and reliable. Making use of this package along with Jboss, which is also free and open, is very useful to the industry. For doing CMP applications, we need one package called mysql-java-connector.we?ve to download it from the driver?s link of www.mysql.com <http://www.mysql.com>.(435KB) (Suresh Babu had written about this in Feb 2004 issue of DeveloperIQ).As both mysql and mysql-java-connector packages are zip files,we unzip them in D:. Now we have all softwares necessary for the experiment..

cd to D:\jboss-3.2.2\server\default\deploy

edit hsqldb-ds.xml as follows

<jndi-name>mysqlDS</jndi-name>

<connection-url>

jdbc:mysql://localhost:3306/STUDENTS

</connection-url>

<driver-class>

org.gjt.mm.mysql.Driver

</driver-class>

<user-name>devasena</user-name>

<password></password>

?STUDENTS? is a database created in MySQL. Don?t give the password. It?ll be automatically recognized by identifying the username. Don?t alter anything other than this.

cd to d:\jboss-3.2.2\server\default\conf>

edit standardjbosscmp-jdbc.xml as follows.

<datasource>java:/mysqlDS</datasource>

<datasource-mapping>MySQL

</datasource-mapping>

Type mapping for MySQL is already defined 

in the file. Leave the remaining contents of

file as it is.

Then edit jbosscmp-jdbc.xml file of our 

application.

<datasource>java:/mysqlDS</datasource>

<datasource-mapping>MySQL

</datasource-mapping>

Remaining things are same.

copy d:\mysql-connector\connector\

mysql-connector.jar

to d:\jboss-3.2.2\server\default\lib

Directory name and the jar filename mentioned above is a renamed one. (Please don?t search for the above given name exactly. There is only one jar file in the connector package).

If we forget to do this step, Jboss won?t connect to mysql. It won?t find the url and driver class.

Code for all ejb files and servlet are same as given in the CMP-Hypersonic part. After making all these alteration, create a ejb jar file as usual and deploy it in Jboss. During deployment, Jboss checks the database configuration details and the one used in our application. If it coincides, then ejb jar will be successfully deployed. Otherwise it throws exception. Now we can execute EJB by writing servlet program which is deployed in tomcat4.1.

In the next edition, we will complete this tutorial on JBoss3.2 , with the method of deploying a BMP and using it. We will also see, the concept of *.war & *.ear files and how to create and use them. After that, we will see how we can use the
built-in Tomcat in JBoss3.2.
3