Java J2EE JBoss Ejb With Eclipse 2003
Java J2EE JBoss Ejb With Eclipse 2003
Introduction....................................................................................................................................................................... 2
Environment ...................................................................................................................................................................... 2
DOWNLOAD J2EE.......................................................................................................................................................... 3
Eclipse................................................................................................................................................................................ 3
Download and install...................................................................................................................................................... 3
Create a simple HelloWorld program.............................................................................................................................. 3
JBoss .................................................................................................................................................................................. 6
Download and install...................................................................................................................................................... 6
Configuring Eclipse to work with JBoss .......................................................................................................................... 7
‘HelloWorld’ as a stateless session EJB. ........................................................................................................................... 8
Introduction............................................................................................................................................................... 8
Make a new project for our server code. ...................................................................................................................... 8
Make the sessionbean.................................................................................................................................................. 8
Create the remote interface ......................................................................................................................................... 9
Create the home interface ........................................................................................................................................... 9
Package the bean into a JAR to be deployed on JBoss .................................................................................................. 9
Deploying the bean................................................................................................................................................... 10
Changing our client to use the bean .......................................................................................................................... 11
Running and debugging............................................................................................................................................ 12
Accessing a database.......................................................................................................................................................... 13
Introduction................................................................................................................................................................. 13
MySql .......................................................................................................................................................................... 13
JDBC Driver for MySql :.............................................................................................................................................. 16
Download and install ANT........................................................................................................................................... 16
Middlegen : generate EJB ............................................................................................................................................. 17
Adapting config/database/mysql.xml......................................................................................................................... 17
Adapt Build.xml ....................................................................................................................................................... 17
Generate EJB’s.......................................................................................................................................................... 19
Back to eclipse : update the server application to read the database ................................................................................ 20
Add the beans to the project ..................................................................................................................................... 20
Modify the session bean to get its data from the entity beans ..................................................................................... 21
Modify, run and debug the client.............................................................................................................................. 24
JSP................................................................................................................................................................................... 26
Required setup ............................................................................................................................................................. 26
Download and install Apache Tomcat....................................................................................................................... 26
Download and install ‘Sysdeo Eclipse Tomcat Launcher plugin’................................................................................ 27
Download and install ‘Solar Eclipse’.......................................................................................................................... 28
A Simple JSP example : WhatTimeIsIt.......................................................................................................................... 29
Building and debugging a lot-of-tiers J2EE web application .............................................................................................. 33
View-Controller (the model will come later) ................................................................................................................. 33
A first view ............................................................................................................................................................... 33
Some More Views (we would not need a controller otherwise) .................................................................................. 34
Then comes the controller ........................................................................................................................................ 36
Add the Model ......................................................................................................................................................... 42
Store and get preferences and settings in XML files ........................................................................................................... 42
What’s next ...................................................................................................................................................................... 42
Introduction
It all started with the article ‘Working with Java – Enterprise Java’ on Apples website. It showed that enterprise Java on OS X
was possible, that everything worked. But it left me somewhat unhappy. As I am very GUI minded – I would not be a Mac
user if I wasn’t – I wanted an IDE that could help me with my OS X enterprise java stuff, and nowhere in that article was
any hint to such an IDE. Secondly, but very related, I want to debug my server code. And last but not least, I do not want to
spend my time writing repetitive code or code that can easily be generated. Just think about EJB-JAR.XML, a good part of
jboss.xml and even the ejb’s and their interfaces–all these getters and setters - they can easily be generated from the lay-outs
of your database..
Fortunately, I got involved in a big J2EE project, exchanging messages between unrelated services via XML and https. We
choose J2EE as the platform to implement our part of it, and JBoss as our application server.
The environment at work is Windows plus Oracle. For this article, I replaced the Oracle database by MySql, and Windows
by OS X. All the rest stayed the same. If you prefer another database, you can do so. This article describes the necessary steps
to make JBoss work with MySql. Doing this for another database is quite similar. If you want to use Windows or *nix, you
can as well: all the software used trough this article is available on all these platforms.
The IDE used is Eclipse, a free product written by IBM and backed by others (Borland being one of them). Although it lacks
some of the flashy features offered by commercial IDE’s (just think of GUI-editors, wizards…), it is very good at what it
does, and its performance is acceptable. It is even usable on a Pismo 500 MHz PowerBook, although you’ll better have the
fastest dual G4 at hand if you are using it on a daily basis. Eclipse has an extensible plug-in architecture. The integration
with JBoss is handled by such a plug-in to name one. No doubt GUI-editing, EJB-generation and others will be added as
plug-ins later. (If you all register WhereDidAllMyMoneyGo?, I could do this myself).
As stated earlier, MySql is the database system I use. To generate ‘stupid code’, I am using a command line tool called
Middlegen. JBoss is my application server, Tomcat my webserver. All these tools are available for free under a GNU licence.
Later, I might add a chapter on version control (using CVS), a chapter on XML (using Castor), but currently, I’ll limit
myself to session and entity beans, and to JSP and servlets.
One last thing: if you do not know what an EJB is, what the difference is between a session and an entity bean, and what a
local and a remote interface is, I suggest you read the relevant chapters of Suns J2ee tutorial first.
This document is pretty much written as a step-by-step instruction – making sense only when you repeat everything that is
described on your own machine while reading.
Oh yes, one more thing: I did not pay any attention to formatting and layout. Sorry for the ugly headers – they are what
Microsoft gave me.
Environment
All the stuff described in this article was written and tested on a dual GHz Quicksilver G4 running OS X 10.2.1. 10.2 is a
prerequisite for Eclipse – threads on Apples Java developer mailing list learn that people using 10.1 have difficulties running
Eclipse. A second prerequisite is a fast Internet connection. There is over 100 megabytes to download if you want to replay
this article.
I unzipped or unstuffed all downloads with Stuffit Expander. You MUST use Stuffit Expander version 7.0 or later, as earlier
versions make a mess of long filenames.
Everything I downloaded just worked as advertised for me after unstuffing. I do not have any unsupported tools, cracked or
doubtful software or haxy installed, so my system is quite out-of-the-box.
As I am not a command line freak, I did not change the configuration of my terminal application. If you use another shell, I
guess you know enough of Unix to adapt the few Unix commands presented in this document so they work with your shell.
And yes, I have the latest version of Apples developer tools installed. (Don’t know if it is required though.)
DOWNLOAD J2EE
The first download – although not really required - is Suns J2ee sdk. This SDK contains a lot of Java classes and some java
tools that you might need to build and run J2EE applications. It can be downloaded from
http://java.sun.com/j2ee/sdk_1.3/. (Id did not download the 1.4 version, as OS X java is still at 1.3.1). Just download and
unzip it. I unzipped it to Aa folder named /Applications/java/j2sdkee1.3.1.
This download is not really necessary for the examples of this article. All I did with this download was to include the file
‘j2ee.jar’ in my projects. J2ee.jar contains the interfaces implemented by enterprise beans. But these interfaces are – if you
search a bit – included in jar-files that come with JBoss as well. But as I had downloaded the sdk earlier on alraedy, I just
used it without looking further. But pf course, including the full J2ee.jar file in a J2ee application is overkill.
When you finished installing the j2ee-sdk, it might be a good time to read trough Suns excellent J2EE tutorial, available
from java.sun.com as well.
Eclipse
Download and install
First of all, Eclipse requires OSX 10.2 or later. If you are running on 10.1x, you should repackage eclipse (doing things with
the info.plist file amongst other things. There is a thread on this on Apples Java developer mailing list).
Eclipse can be downloaded from http://www.eclipse.org/downloads/index.php.
The latest OSX builds are currently in the ‘Stable build’ category, next to the M1 build name. Future builds will appear in
the ‘Latest Release’ category. The current stable build weights about 57 Mb. Download it and unzip it with a version of
Stuffit Expander later than 7.0. (You might have to add the .zip extension to the file in order for the system to identify it as a
zip archive.). If you have an older version, you should use the command line tools that come standard with OSX to unzip.
The result of the download process is a folder called ‘Eclipse’ that contains, well, Eclipse. Just move this folder to the
‘Applications’ folder.
You launch Eclipse by double-clicking it. Note that the help does not seem to work in the current stable build.
Then close Eclipse and restart it. My version complains that it is not able to restore the current workspace (which is the
welcome screen), but once you dismissed that dialog, it should work Ok.
- Give your project a name (I named it HelloProject) and a location (I kept the default, which is inside the ‘Eclipse’
folder – bad choice me thinks) and press ‘Next>>’ again.
- On the next screen, check the ‘Use source folders contained in the project’ button, push the ‘Create New Folder…’
button and name the source folder ‘src’. Answer ‘Yes’ when Eclipse suggests you to place builds in a build folder as
well. Next Press ‘Finish’.
- Next thing to do is to create our program. Control-click the HelloProject folder and select ‘New Class’ from the
contextual menu and fill in the dialog. Note that you cannot use the <Tab> key to move between form fields. <Tab>
will just insert a tab into the current field. The dialog should be like this when filled:
I checked ‘public static void main…’ so my class would have a main method. The package name was chosen to avoid
name collisions with all the other HelloClients out there in cyberspace. When you next press ‘Finish’, you should get
this:
- As I do want my curly brackets to appear on a new line, I opened the ‘Window->Preferences’ dialog, scrolled to the
‘Java->Code Formatter’ category and checked ‘Insert a new line before an opening brace’, ‘insert new lines in control
statements’ and ‘Clear all blank lines’. To apply these formatting rules to existing sources, control-click the editor pane
and select ‘Format’ from the contextual menu.
- Next we complete the main method. It should be
- Then click on the little arrow next to the ‘Bug’ button, and select ‘Debug as->Java Application’ from the menu.
- You will be asked to save your source (saving and compiling are linked in Eclipse). Answer ‘yes’. Eclipse should now
switch from ‘Resource’ perspective to debug perspective, launch your program, and display its results in the console
(the pane at the bottom of the debug perspective).
- If you would like to debug your program, just double-click in the margin next to the statement onto which you want
the debugger to break.
- To switch back from debug perspective to resource perspective, click the little ‘resource perspective’ button on the left
of the main window (the button showing a clipboard and a folder). A perspective is just a set of open panes that are
suitable for a specific task. Please consult the Eclipse documentation if you want to learn more about perspectives.
JBoss
Now we are going to split our application in two parts: the interface and the business logic. The business logic can say ‘Hello
World’; the interface can display whatever the business side says. Big advantage of this approach is that we can put different
‘Interfaces’ onto our business logic: terminal clients, web clients, GUI-clients etc…, all linked to the same unique business
code that gets the real work done. Or we can share the same business logic between different applications.
To do this, we need an application server to host the business part. We choose JBoss – a freeware J2EE application server –
for this purpose. JBoss itself is an EJB container. It comes bundled with Jakarta Tomcat or Jetty to serve web pages, JSP
pages and Servlets. You could run both JBoss and Tomcat (or Jetty) on different machines if you wanted. In a
production/internet environment, it is wise to do so: Tomcat or Jetty will then run outside the firewall, just handling
Internet traffic. JBoss will do the real business work from a server inside your firewall. As that server must have access to
resources like databases etc, it is saver to keep in inside your firewall.
But for our example application, we will use the standard installation with JBoss and Jetty tied together.
Prompt>cd /applications
Prompt>cd jboss-3.0.3
Prompt>cd bin
Prompt>./run.sh
You will now get a lot of messages, ending with (if everything went fine)
Now just press <Ctrl><C> to terminate JBoss again, as we will use Eclipse to run and control JBoss.
- Now open the preferences dialog (window->preferences), you’ll notice a new item in the on the left of the dialog
named ‘JBoss’. Select it and set the JBoss Home directory to where it is (in my case, it is /Applications/jboss-3.0.3).
Just leave the rest as it is. Press ‘Apply’ and ‘Ok’. (Not sure about the apply, but it does not hurt)
The result of this is that you have, when being in resource perspective (or any perspective you customized) a new JBoss menu
that allows you to start and stop JBoss from within Eclipse. There are 2 new buttons in the toolbar ( ) to start and
stop JBoss as well. Just start and stop JBoss to see what happens.
- Press ‘Finish’.
- A new class that implements all required sessionbean methods will be generated and opened in the editor. It just lacks
an ejbCreate method, so it cannot be used as is. So we add a parameterless ejbCreate method:
- Note that, as soon as you finished typing, the word ‘RemoteException’ will be underlined. Eclipse does compile as
you type, and all things it cannot compile right away, will be underlined. In our case, this is because the package
containing ‘RemoteException’ is not yet imported. To do this, press <Cmd+space> while the cursor is placed just after
the word ‘RemoteException’. Eclipse will add the necessary imports for you. Nice!
- Next, we create the JBoss.xml file the same way. This file will link the JNDI-name ‘ejb/HelloServer’ to the EJB named
‘HelloWoldServer’ . Here is what it looks like:
- In the last dialog, check ‘save the description of this jar in the workspace’ and name the file
‘/HelloServer/Builddescription.jardesc’. Uncheck ‘Export class files with compile errors’. Press ‘Next>’ and ‘Finish’.
- Just double-click the newly generated file (builddescription.jardesc). It is standard XML that tells Eclipse how to make
a Jar from our project.
package org.berttorfs.TutorialClients;
import java.util.Properties;
import javax.naming.InitialContext;
import org.berttorfs.tutorialserver.HelloServer;
import org.berttorfs.tutorialserver.HelloServerHome;
Accessing a database
Introduction
The j2ee environment contains entity beans to connect to and communicate with databases. An entity bean represents one
table in a database. Reading from and writing to databases is done via the entity beans. The first implementation of entity
beans forced one to communicate with these beans via a remote interfaces – as if they were running on a different machine.
In most cases however, session beans and entity beans are all running on the same machine. Since version 2 of the EJB
specifications, entity beans can be accessed via a local interface, which is much faster if your beans are all deployed on one
server.
Entity beans are just an abstraction layer above your database system, nothing more, nothing less. They deal with input-
output, transaction management etc…, not with business logic. Business logic should be implemented elsewhere. Maybe I
add a section on business logic and how it could be implemented later to this article.
Entity beans are not that hard to do, but there are an awful lot of things to do to create them. Fortunately, most of this stuff
is stupid repetitive typing work that can be automatically generated from our database scheme. And that is what we will do
in this chapter. We will first download and install MySql and create a sample MySql database with some sample data. Next,
we will download and install a JDBC driver for MySql. Then comes ANT, a free build tool required to pilot Middlegen. We
will use Middlegen (yep, another download) to generate EJBs from the database structure and Xdoclet (no, not another
download, as it comes bundled with Middlegen) to generate the necessary interfaces from tags set in the EJBs by Middlegen.
Nice thing about Middlegen and Xdoclet is that they also generate sample JBoss.xml and ejb-jar.xml files, so we just have to
copy and paste the additional XML in our current files to deploy the entity beans.
Once our entity beans are done, we will change our session bean (the HelloServer bean) to read from the database and send
the result of the read back to the client. The client will the list whatever the server read from the database.
So lets start by setting up our database:
MySql
- Download the MacOsX build from http://www.MySql.org. (http://www.mysql.com/Downloads/MySQL-3.23/mysql-
3.23.53-apple-darwin6.1-powerpc.tar.gz)
Prompt>Cd /applications
Prompt>Cd my<tab><enter>
- The <tab> stands for the tab-key. As the applications folder contains only one folder starting with ‘my’, typing <tab>
will make the terminal finish the rest of the command by substituting ‘my’ with mysql-3.23.53-apple-darwin6.1-
powerpc, saving you a lot of typing work.
If you never used MySql before, you must initialize some MySql system tables. This is done by executing a script that resides
in the scripts folder inside the MySql folder. Just type
Prompt>./scripts/mysql_install_db
Preparing db table
Preparing host table
Preparing user table
Preparing func table
Preparing tables_priv table
Preparing columns_priv table
Installing all prepared tables
021031 18:47:42 ./bin/mysqld: Shutdown Complete
To start mysqld at boot time you have to copy support-files/mysql.server
to the right place for your system
PLEASE REMEMBER TO SET A PASSWORD FOR THE MySQL root USER !
This is done with:
./bin/mysqladmin -u root password 'new-password'
./bin/mysqladmin -u root -h D5760ED6.kabel.telenet.be password 'new-password'
See the manual for more instructions.
You can start the MySQL daemon with:
cd . ; ./bin/safe_mysqld &
You can test the MySQL daemon with the benchmarks in the 'sql-bench' directory:
cd sql-bench ; run-all-tests
Please report any problems with the ./bin/mysqlbug script!
The latest information about MySQL is available on the web at
http://www.mysql.com
Support MySQL by buying support/licenses at https://order.mysql.com
Prompt>./bin/safe_mysqld --user=mysql&
The & at the end of the command launches the command in batch mode so you can continue typing in commands in your
terminal.
The previous command creates the mysql database which will hold all database privileges, the test database which you can
use to test MySQL, and also privilege entries for the user that run mysql_install_db and a root user (without any passwords).
It also starts the mysqld server.
Next we are going to do some tests:
Prompt>Cd bin
Prompt>./mysqladmin -u root drop test.
Whenever you need MySql, you can start it from within the MySql folder with the command
Prompt>./bin/safe_mysqld
It is a good idea to set a root password for the database (not to be confused with your systems root password. In the
command below, we assign a password ‘verysecret’ to the root account. When prompted for the current password, just press
enter, as the root account has no password yet.
Prompt>Cd bin
Prompt>./mysqladmin -u root -p password verysecret
Enter password:<enter>
So far for installing and configuring MySql. We will now start an interactive MySql session and create a database with some
tables. To keep everything simple, we will do that using the root account. So, from within the bin directory, we type
Prompt>./mysql -u root -p
Prompt>Enter password:
When prompted for a password, type whatever password you assigned (we used ‘verysecret’). Whatever you type will not be
shown, so somebody looking over your shoulder cannot steal your password. The system will respond with:
Mysql>exit;
This does not stop MySql. The database is still running, waiting for incoming connections. To shutdown, you should type,
from within the MySql bin directory,
The file named ‘.tcshrc’ is in your home folder (if it is not, you must create it). You’ll need an editor that can read hidden
files (like Metrowerks Codewarrior or BBedit or plain old VI - from the command line) in order to do so. If you use another
shell, you probably know enough of Unix to know what file you must modify to customize your shell.
Adapting config/database/mysql.xml
The Middlegen folder contains a subfolder named samples, which contains a folder named config which contains a folder
named database. Inside that folder, there is the mysql.xml file we need. Just save a copy of the original file to be sure. Then
open mysql.xml and change it like this:
What the values of database driver and database url mean and how the are assembled is described in the documentation that
came with the ODBC driver we use.
Adapt Build.xml
The /Samples folder contains a sample build.xml file. We have to modify it slightly:
First of all, we change
<!DOCTYPE project [
<!ENTITY database SYSTEM "file:./config/database/hsqldb.xml">
<!ENTITY ejb SYSTEM "file:./config/ejb/jboss.xml">
]>
to
<!DOCTYPE project [
<!ENTITY database SYSTEM "file:./config/database/mysql.xml">
<!ENTITY ejb SYSTEM "file:./config/ejb/jboss.xml">
]>
This instructs Middlegen to use the info contained in mysql.xml – the file we just edited - to connect to our database.
The next line, we change to
<property file="${basedir}/build.properties"/>
<property name="name" value="org.berttorfs"/>
This just names our project. Next, we scroll down until we see
in that area, we alter the code so it looks like this. I put the things I modified in bold:
<!--
We can specify what tables we want EJBs generated for.
If none are specified, EJBs will be generated for all tables.
Comment out the <table> elements if you want to generate for all tables.
Also note that table names are CASE SENSITIVE for certain databases,
so on e.g. Oracle you should specify table names in upper case.
-->
<!--table generate="true" name="persons" pktable="persons_pk"/>
<table generate="true" name="flights" pktable="flights_pk"/>
<table name="reservations"/-->
<!--
If you want m:n relations, they must be specified like this.
Note that tables declare in multiple locations must all have
the same value of the generate attribute.
-->
<!--many2many>
<tablea generate="true" name="persons"/>
<jointable name="reservations" generate="false"/>
<tableb generate="true" name="flights"/>
</many2many-->
<cmp20
destination="${build.gen-src.dir}"
package="${name}.ejb"
interfacepackage="${name}.interfaces"
jndiprefix="${unique.name}"
pkclass="true"
dataobject="false"
viewtype="local"
mergedir="${basedir}/src/middlegen"
readonly="false"
fkcmp="true"
guid="false"
>
>
<!-- Let the EJBs use The Sequence Block PK generation pattern‡
<!-- <sequenceblock
blocksize="5"
retrycount="2"
table="SEQ_BLOCK"
next, we set the logical name of the database our EJBs have to connect to. This logical name will appear in the generated
jbosscmp-jdbc.xml (see further), and will be linked with a physical database server via configuration files of JBoss later on:
<taskdef
name="ejbdoclet"
classname="xdoclet.modules.ejb.EjbDocletTask"
classpathref="lib.class.path"
/>
.
.
.
<jboss
version="3.0"
xmlencoding="ISO-8859-1"
destdir="${build.ejb-meta.dir}/META-INF"
validatexml="true"
datasource="java:/MySqlDS"
datasourcemapping="${jboss.datasource.mapping}"
/>
</ejbdoclet>
</target>
(In the snippet above, I just removed the sentence ‘depends="postprocess-ejb-jar"). This modification unlinks the generation
of the entity beans from the generation of the interfaces and the xml. Middlegen will now stop after it generated the EJBs.
We must launch it again with the target name ‘ejbdoclet’ in order to generate the interfaces and the xml files. I had to do this
because, for one reason or another, the ANT job refuses to continue after the Middlegen step.
Generate EJB’s
This is the easier step. Just navigate in the terminal to the place where your modified ‘build.xml’ resides and enter
Prompt> cd /applications/middlegen-2.0-b1/samples
Prompt>ant middlegen
You will get a lot of text back from ant, and the following window will open (you might have to resize things a little, play
with the split bar and shuffle the tables around to make it look like the screen dump below):
Click on each of the tables and verify if the checkbox ‘remote’ is not checked. As we will only access our database via its local
interface, we do not want to generate remote interfaces. There are no relationships drawn between the tables neither. MySql
currently does not support referential integrity on its native tables (the ones we created – it does offer some other table types
that support referential integrity though. Just take a look at the manual if you want to know how to do it.).
When finished checking, just press ‘Generate’ and quit the GUI application.
Then run Ant again. This time, we will generate the necessary interfaces and some deployment descriptors.
Prompt>ant ejbdoclet
This will generate all interfaces and some utility classes. All generated classes are in the samples/build folder inside the
Middlegen folder.
Now our generated beans are part of our project, and we can start using them.
Modify the session bean to get its data from the entity beans
Up to now, all our session bean could do, was to return the string "Hello World, this is your sessionbean speaking!" via its
method sayHello. We will now add another method called ‘getPartCatalog’ which returns an array of partCatalogEntries.
These entries will be read from the database. We will
- Create a class ‘partCatalogEntry’ to hold our catalog entries. This class – or an array of it - will be passed between our
sessionbean and a client somewhere on the network.
- We will add a method to our sessionbean that returns an array of partCatlogEntry objects
- We will write code for that method; It should get its data from the part and the partgroup table.
- We will modify our deployment descriptors.
- Next, we will deploy our new sessionbean to JBoss.
- And finally, we will adapt our client to call our new getPartCatalog method.
So lets go:
- Now select the 5 variables, right click and select ‘source->generate getter and setter’ from the contextual menu. Select
all the proposed setters and getters in the window that shows next, and bingo, ready is your class! Save your file.
Of course, this will not compile. There are uncaught exceptions. To generate them automatically, we select the block of code
where uncaught exceptions are thrown (this block start just below the comment on PartGroupUtil and continues until the
return statement – the return statement not included) and right click. Select ‘Source->surround with try-catch block’ from
the contextual menu. And Eclipse will do its magic again, adding the try, the braces and
catch (NamingException e)
{
}
catch (FinderException e)
{
}
No need to memorize all the exceptions thrown by the methods you call. Eclipse does it for you.
ejb-jar.xml
Open the file ejb-jar.xml that was generated by Middlegen (/applications/Middlegen-2.0-b1/samples/build/ejb-meta/META-
INF/ejb-jar.xml and copy the complete section starting with <!-- Entity Beans --> and ending with the last </entity> (we
have 2 entity beans, so the <entity> section appears twice.). Paste it in the ejb-jar.xml file of our project.
jboss.xml
Copy the tho <entity> sections into jboss.xml of our project. (after the </session> tag and before the </enterprise-beans> tag.
Jbosscmp-jdbc.xml
Create a new file named jbosscmp-jdbc.xml into the META-INF folder of our project. When it opens in the editor, just
copy the contents of the generated file with the same name in it. Notice the first few lines:
<jbosscmp-jdbc>
<defaults>
<datasource>java:/MySqlDS</datasource>
<datasource-mapping>mySQL</datasource-mapping>
</defaults>
<enterprise-beans>
<entity>
<ejb-name>Partgroup</ejb-name>
<table-name>partgroup</table-name>
…
They tell that the jdbc-datastore to use for all entity beans that follow is called java:/MySqlDS. This datastore has to be
defined somewhere to JBoss, so it can connect to the right database at runtime. That is what we will do in the next step.
<attribute name="JndiName">MySqlDS</attribute>
<attribute name="JndiName">MySqlDS</attribute>
Note that userId and password are hard coded in our deployment descriptors, which may not be the safest way to do so. But
if our server is locked away in a computer room, only accessible by trusted people, it might not be as bad as it seems. When
finished editing, copy the file to /applications/jboss3.0.3/server/default/deploy/.
A last file to modify is
In the file /applications/jboss-3.0.3/server/default/conf/standardjbosscmp-jdbc.xml
This file describes the default behaviour of our database connection. Open it and add change the defaults section as follows:
(things I changed are bold).
<defaults>
<datasource>java:/MySqlDS</datasource>
<datasource-mapping>mySQL</datasource-mapping>
<create-table>false</create-table>
<remove-table>false</remove-table>
<read-only>false</read-only>
<time-out>300</time-out>
<pk-constraint>true</pk-constraint>
<fk-constraint>false</fk-constraint>
<row-locking>true</row-locking>
<preferred-relation-mapping>foreign-key</preferred-relation-mapping>
<read-ahead>
<strategy>on-load</strategy>
<page-size>1000</page-size>
<eager-load-group>*</eager-load-group>
</read-ahead>
<list-cache-max>1000</list-cache-max>
</defaults>
As we want our database to keep living without any application, we set the create-table and remove-table attributes to false. I
set the row level locking to true as well.
System.out.println(theHelloServer.sayHello());
In stead of the method ‘sayHello’, we will now call update our source to call our servers method
Our server does not use the argument named ‘inPartGroup’, so we could pass anything we want.
The main method of our updated client looks like this :
Now run in, debug it (yes, you can debug your server code) and do anything with it you want.
JSP
Lets move from the server to the client now. Eclipse, together with some freely available plug-ins, allows us to write, debug
and deploy web sites using J2EE technologies (servlets and Jsp, it is). To deploy J2EE web applications, we need a web server
that is able to read, unzip, compile and execute servlets. To run jsp pages, we need a web server that can transform jsp pages
into servlets, compile and execute them.
Although JBoss comes with Jetty installed (Jetty is such a web server), we will use a standalone Tomcat installation for our
webserver. The reason for this is that I do not know of any Eclipse plug-in that lets you debug jsp pages when running Jetty
within Jboss. I do know about a plug-in that lets you debug jsp pages when running with a standalone Tomcat. So that is
what we will to.
Later, when we know how to make and debug simple JSP pages, we will go back to Jboss and make our JSP client
communicate with our sessionbean.
Here is an outline of what we will be doing next:
- Downloads and installs:
- Apache Tomcat
- Sysdeo Tomcat plugin
- Solar Eclipse
- Make and deploy a simple JSP page.
- Make and deploy a 2 page JSP application with a little controller servlet.
- Share data between these 2 pages using java beans
Required setup
Download and install Apache Tomcat
http://jakarta.apache.org/
I downloaded the file tomcat-4.1.18.zip and unzipped it into my Applications folder. And that is basically all there is to do.
Be sure that the environment variable ‘JAVA_HOME’ is declared. I added the declaration of JAVA_HOME to my .tcshr file
:
The file named ‘.tcshrc’ is in your home folder (if it is not, you must create it). You’ll need an editor that can read hidden
files (like Metrowerks Codewarrior or BBedit or plain old VI - from the command line) in order to do so. If you use another
shell, you probably know enough of Unix to know what file you must modify to create environment variables.
To start Tomcat, open a terminal, navigate to applications/jakarta-tomcat-4.1.18/bin, and enter the following:
Prompt> cd applications/jakarta-tomcat-4.1.18/bin
Prompt> ./startup.sh
Using CATALINA_BASE: /applications/jakarta-tomcat-4.1.18
Using CATALINA_HOME: /applications/jakarta-tomcat-4.1.18
Using CATALINA_TMPDIR: /applications/jakarta-tomcat-4.1.18/temp
Using JAVA_HOME: /Library/Java/Home
Next, you can test your installation by opening a web browser and navigate to http://localhost:8080/. (or
http://127.0.0.1:8080/ if your browser says that dns failed to locate localhost, as my chimera did). If everything went well,
you should see this:
If Tomcat fails to start, complaining that port 8080 is already occupied, you probably have Jboss still running. Jboss comes
with Jetty, which is another Web server that is configured to use port 8080. So be sure that you shut down Jboss before
starting Tomcat.
Once you have Tomcat working, shut it down, As we will be control it from within JBoss.
Prompt> cd applications/jakarta-tomcat-4.1.18/bin
Prompt> ./shutdown.sh
Using CATALINA_BASE: /applications/jakarta-tomcat-4.1.18
Using CATALINA_HOME: /applications/jakarta-tomcat-4.1.18
Using CATALINA_TMPDIR: /applications/jakarta-tomcat-4.1.18/temp
Using JAVA_HOME: /Library/Java/Home
Prompt>
Setup
- Select (when being in resource perspective) ‘Window->Customize Perspective’ from the menu.
- Check ‘Tomcat’ in the category ‘Others’.
- Repeat these steps for all the perspectives from where you want to start or stop Tomcat.
- Select the menu ‘Window->Preferences’ and tell Sysdeo where it can find Tomcat.
You should now have a new menu called ‘Tomcat’ from where you can start and stop Tomcat. (yes, you can try it
now).
- Enter a name for your project (I called it WhatTimeIsIt) and press ‘Next>’.
- The dialog that opens next opens only when you choose ‘Tomcat Project’ from the ‘New’ dialog. It is part of the
Sysdeo plug-in. As the context name, I entered ‘timeServer’. We will have to use that context name later to connect to
the web application we are building. I also checked the ‘Can update server.xml’ checkbox. If you check this, the
Sysdeo plug-in will make all the changes necessarily to deploy our project in Tomcat for us. If you are an experienced
Tomcat administrator, you can leave this checkbox unchecked.
- Press ‘Finish’.
- If you now look at the Server.xml configuration file of Tomcat, you will see that the line
was added just beforte the </Host></Engine></Service> closing tags. Sysdeo did this because you checked the ‘Can
update server.xml checkbox.
- Next, we create a simple JSP page. Choose <file->new->file> from the menu.
- Create the new file at the root of our new project. I named the new file ‘timeTeller.jsp’.
- Press ‘Finish’. You will now the contents (empty) of timeTeller.jsp in the edit pane of Eclipse. Enter the following and
save the file :
JSP pages are transformed into servlets before the are compiled and executed. So debugging JSP at the source level is not
possible. If you use the Sysdeo pluging, you can debug the servlet code that was generated from the JSP page. To do so, you
must follow the next steps :
- Select the work-directory of your project and select ‘refresh’ from the contextual menu
- Now navigate into the org.apache.jsp tree until you arrive at the file name ‘timeTeller_jsp.java. That file contains the
servlet code that was generated from your jsp. You can put breakpoints in that file as you can do in any other java file.
Just place a breakpoint before the line that says
out.print( (new java.util.Date()).toLocaleString() );
A first view
Once our project is created, we add the page ‘GetInfo.jsp’ at the root of our project.
- <Control-Click> the AdultWebSite project and choose ‘New file’ from the contextual menu.
- Choose the project root as the place to store the file, and enter ‘GetInfo.jsp’ as the name of the new file.
- The new file will be opened in the editor pane. Enter the following code :
- Pressing the ‘Let me in’ button will bring you nowhere (to a Tomcat error page to be exact, which is close to
nowhere).
- Then <Ctrl-Click> the newly created JSP folder. Select <New->File> from the contextual menu and name the file
Adults.jsp. Then put something like this in that file :
<%@ page contentType="text/html;charset=windows-1252"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Model-Controller Test
</title>
</head>
<body>
<h2>
This page is only to be viewed by mentally healthy people over 18.
</h2>
<p>
</p>
</body>
</html>
- Save the file
- Create another file ‘Children.jsp with the following contents
<%@ page contentType="text/html;charset=windows-1252"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Model-Controller Test
</title>
</head>
<body>
<h2>
This is a page suited for children
</h2>
<p>
</p>
</body>
</html>
- Give the class a name and a location as shown in the screenshot below. Make the class inherit from httpServlet.
- Then edit the file and add the following XML (I copied the initial version from the web.xml file from the conf
directory).
<servlet-mapping>
<servlet-name>Process</servlet-name>
<url-pattern>/SiteController/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>GetInfo.jsp</welcome-file>
</welcome-file-list>
</web-app>
- The first <servlet> tag and its matching <servlet-mapping> tag links the servlet named
org.BertTorfs.AdultWebSite.AdultWebSiteController to the URL
http://machine:Port/AdultWebSite/SiteController/*. The ‘*’ can be anything, so we can have multiple URLs that all
go to our controller servlet. You do not have to specify the context root (/AdultWebSite) in the servlet mapping.
- We also added an entry to the welcome-file list. That way, just typing AdultWebSite will bring us to our opening
page.
- Now put a breakpoint inside the ‘doAnything’ method of the servlet, fire up Tomcat, and open your favorite browser
on the page http://127.0.0.1:8080/AdultWebSite/ (I am behind a proxy, so localhost does not work for me. Your
mileage may vary). You can omit the ‘index.jsp’ from the URL, as that was specified as the welcome-file.
- When the page opens, press the ‘Let me in’ button.
- Your servlet will be opened in the source pane with the line where you placed a breakpoint selected. As your
debugging holds up the execution of the request, chances are that your browser will give an error, telling that your site
could not be opened in a reasonable time.
- Open the variables pane of the debug perspective, and click on the small ‘+’ next to ‘Request’. You’ll see something
like this :
ls_NextPage = null;
if (ls_action.compareToIgnoreCase("/WhichPage".toString()) == 0)
{
long ll_year;
try
{
ll_year = Long.parseLong(ls_year);
if (ll_year <= 1985)
{
ls_NextPage = new String("/WEB-INF/JSP/Adults.jsp");
}
else
{
ls_NextPage = new String("/WEB-INF/JSP/Children.jsp");
}
}
catch (NumberFormatException e)
{
ls_NextPage = new String("/WEB-INF/JSP/InvalidInput.jsp");
}
}
if (ls_NextPage == null)
ls_NextPage = new String("/WEB-INF/JSP/InvalidInput.jsp");
doForward(ls_NextPage, request, response);
}
- And test the page. Start Tomcat, open the URL http://127.0.0.1:8080/AdultWebSite/, and press the ‘Let me In’
button without entering anything. You should see this :
- Go back, and enter 2002 as the year of birth. You should see this
- Go back, enter 1875 as the Birthdates year, and you’ll get this:
What’s next
Next comes logging, Strut, writing an eclipse plugin that calls Middlegen straight from within a database browser running in
Eclipse, communicating with clients running on Palm or Symbian devices over Bluetooth etc…. When time allows, I’ll
complement – or write new articles – on the topics described above. If all of you register a copy of
WhereDidAllMyMoneyGo?, I could start writing tomorrow :). Otherwise, you will need some more patience.
Bert Torfs