Vous êtes sur la page 1sur 104

J2EE – Working with JBoss

Lab Hand-on
1 Tutorial Preparation 3
1.1 Introduction......................................................................................................... 3
2 The Project .................................................................................................................. 3
3 JSP Project .................................................................................................................. 8
3.1 Creating the JSPs ................................................................................................ 8
3.2 The J2EE Application ....................................................................................... 12
3.2.1 Creating the application.xml..................................................................... 12
3.2.2 The Packaging........................................................................................... 17
3.2.3 MyAppWeb.war creation.......................................................................... 18
3.2.4 MyApp.ear creation .................................................................................. 22
3.3 JBoss Configuration and Launch ...................................................................... 29
3.4 Deployment....................................................................................................... 35
4 The Servlet and the Web-App................................................................................... 38
4.1 Creating the JSP and Servlet Files .................................................................... 38
4.2 Generation of the Servlet related files .............................................................. 43
4.2.1 XDoclet Web Configuration Creation ...................................................... 43
4.2.2 MyAppWeb.war configuration ................................................................. 52
4.3 Deployment....................................................................................................... 58
5 The EJB..................................................................................................................... 61
5.1 Creating the EJB ............................................................................................... 61
5.2 Generation of the EJB related files ................................................................... 67
5.2.1 XDoclet EJB Configuration Creation ....................................................... 67
5.3 Modifying the servlet........................................................................................ 75
5.4 The Packaging................................................................................................... 79
5.4.1 MyAppEJB.jar creation ............................................................................ 79
5.4.2 Modify MyApp.ear configuration............................................................. 85
5.4.3 Modifying application.xml ....................................................................... 87
5.5 Deployment....................................................................................................... 88
6 JDBC Project ............................................................................................................ 91
6.1 JDBC Programming.......................................................................................... 91
6.1.1 The Project ................................................................................................ 91
6.1.2 Creating the Java class .............................................................................. 92
6.1.3 Setting Project properties.......................................................................... 95
6.1.4 Running the Project................................................................................... 97
6.2 JDBC Connection from Eclipse........................................................................ 98
6.2.1 The Database Explorer.............................................................................. 98
6.2.2 Creating a new connection........................................................................ 99
6.2.3 Creating SQL Scrapbook ........................................................................ 101
7 Conclusion .............................................................................................................. 104
1 Tutorial Preparation
1.1 Introduction

The goal of this tutorial is to demonstrate how simple it is to develop J2EE applications
with JBoss Eclipse IDE. The sample applications that will be built are J2EE applications,
which compute the Fibonacci suite.

The tutorial is split into several parts:

• The Project: this part shows how the project is prepared (source and build
path)
• JSP Project: this part shows how to write a project which contains two JSP
pages which displays the Fibonacci series till a limit which is input by the user.
• The Servlet and the Web-App: this part shows how to write a Servlet class
which takes input from a JSP and computes the Fibonacci series.
• The EJB: this part shows how to incorporate an EJB class which computes
the Fibonacci series in the previous project.

2 The Project

We will create a source folder, import libraries and make the build path.

Create a new J2EE 1.4 Project. Select File > New > Project... and choose JBoss-IDE >
J2EE Projects > J2EE 1.4 Project.
Enter MyApp for the project name and select the Next button.
Create a source folder named src. For this click the Add Folder button and enter src and
click OK.
Make sure the default output folder will be bin. For this click the browse button and
create a new folder named bin under MyApp.

Now click the Finish button.


In the package explorer, the new project should look like this. Note that the J2EE 1.4 core
classes are directly added. They are available like a standard library with all the source
code.
3 JSP Project

Lets first create a project to display the Fibonacci series up to a user specified limit in
which all the computation logic is in JSPs.

3.1 Creating the JSPs

1. Create a docroot folder under the root of the project.

For this, select the MyApp project. Right click the project. Select New > Folder.

Name the folder as docroot.


2. Create 2 empty files named index.jsp and output.jsp under the docroot
folder.

For this, select the docroot folder. Right click the folder. Select New > file. Name
the file as index.jsp. Repeat the procedure for output.jsp also.

The index.jsp file is intended to be the default page for the Web application.
In the package explorer, the project should look like this.
The following content should be copied into the index.jsp file.This page has to capture
the limit of the series from the user:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">


<html>
<head>
<title>
Fibonacci Application
</title>
</head>
<body>
<h1>Fibonacci Form</h1>
<form action="output.jsp" method="POST" >
<table cellspacing="2" cellpadding="2" border="0">
<tr>
<td>
Limit :
</td>
<td>
<input type="text" name="limit" value="50">
</td>
</tr>
<tr>
<td>
<input type="submit" name="Compute" value="Compute">
</td>
<td>
<input type="Reset">
</td>
</tr>
</table>
</form>
</body>
</html>
The following content should be copied into the output.jsp file.This page computes
and displays the Fibonacci sseries for the given limit.
<html>
<head>
<title>
Fibonacci Computation
</title>
</head>
<body>
<h1>
Fibonacci Computation
</h1>
<p>
<%
int limit = 0;
String value = request.getParameter("limit");
if (value != null)
{
try
{
limit = Integer.parseInt(value);
}
catch (Exception e)
{
}
}
if (limit < 0)
{
throw new Exception("Argument should be positive");
}
double[] suite = new double[limit + 1];
suite[0] = 0;

if(limit!=0)
{
suite[1] = 1;
for (int i = 2; i <= limit; i++)
{
suite[i] = suite[i - 1] + suite[i - 2];
}
}
%>
The <%= limit %> first Fibonacci numbers
<%
for (int i = 0; i < suite.length; i++)
{
%>
<br>
<%= i %> : <%= suite[i] %>
<%
}
%>
</p>
</body>
</html>
3.2 The J2EE Application

Create a folder META-INF in the src folder.

For this, right click the src folder and select New > Folder. Name the folder META-INF.

In the package explorer, the project should look like this.

3.2.1 Creating the application.xml

1. Right click on the src/META-INF folder, and choose New > Other....
2. Choose JBoss-IDE > Descriptors > EAR 1.3 Deployment Descriptor,
and click Next.
Make sure application.xml is the name of the file, and click Finish
Your META-INF directory should now look like this:

To view the contents of the application.xml file , right click application.xml, select Open
With Text Editor
The content in the application.xml file will look like this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE application PUBLIC
"-//Sun Microsystems, Inc.//DTD J2EE Application 1.3//EN"
"http://java.sun.com/dtd/application_1_3.dtd">
<application>
<display-name></display-name>
<module>
<ejb></ejb>
</module>
<module>
<web>
<web-uri></web-uri>
<context-root></context-root>
</web>
</module>
</application>

Now edit the application.xml file by adding MyAppWeb.war between the <web-
uri></web-uri> tag. Add /myapp between the <context-root></context-root> tag.
After saving, the application.xml file should look like this

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


<!DOCTYPE application PUBLIC
"-//Sun Microsystems, Inc.//DTD J2EE Application 1.3//EN"
"http://java.sun.com/dtd/application_1_3.dtd">
<application>
<display-name></display-name>
<module>
<ejb></ejb>
</module>
<module>
<web>
<web-uri>MyAppWeb.war</web-uri>
<context-root>/myapp</context-root>
</web>
</module>
</application>

3.2.2 The Packaging

JBoss Eclipse IDE provides an easy way to configure the packaging of various archives.
There is no restriction of what can be packaged. In this chapter, two packaging
configurations will be defined:

• The Web Application WAR- Contains presentation tier components.


• The J2EE Application EAR - It keeps everything organized. JBoss expands the
EAR, finds the required deployment descriptors, and proceeds from there. For this
exercise it will will contain the Web Application War, as well as the
application.xml deployment descriptor.

Enable Packaging

1. Edit the project properties by right clicking on the project and select
Properties.
2. In the property page, select Packaging Configurations.
3. At the top of the page there is a check-box labeled Enable Packaging. Check
this check-box.
3.2.3 MyAppWeb.war creation

Click the Add button on the right side of the list. Type MyAppWeb.war in the “Name:”
field of the dialog and click OK. You have created a new packaging configuration that
will produce the MyAppWeb.war file.

The screen should look like this:


Select the MyAppWeb.war item and right-click in the area to pop-up the menu and
choose Add Folder.
A Folder Selection dialog appears. This dialog allows to select which folder (local to
workspace or in the file system) to include into the package, to specify include and
exclude filters (A la Ant) and to set a prefix that will be append when building the
package.

Click on Project Folder. A Folder Chooser dialog appears.

This dialog allows selecting which folder to include. This folder can be chosen among all
the opened projects.
Click on Project Folder and select the /MyApp/docroot folder from the Folder
Chooser dialog. This is the content of the Web Application.

Click on OK.
The packaging configuration for the MyAppWeb.war is now complete.

The screen should look like this:

3.2.4 MyApp.ear creation

Click the Add button on the right side of the list. Type MyApp.ear in the dialog and
click OK.

You have created a new packaging configuration that will produce the MyApp.ear file.
To add the application deployment descriptor, select the MyApp.ear item and right-click
in the area to pop-up the menu and choose Add File. A File Selection dialog appears.
This dialog allows you to select which file (local to workspace or in the file system) to
include in the package and to set a prefix which will be appended when building the
package.

Click Project File…

A File Chooser dialog appears.

This dialog allows to select which file to include. This file can be chosen among all the
opened projects.
Choose the file /MyApp/src/META-INF/application.xml.

The application.xml must be located under the META-INF of the EAR package. Set
the prefix to META-INF.

Click on OK.

The screen should look like this:


To add the Webmodule, select the MyApp.ear item and right-click in the area to pop-up
the menu and choose Add File. A File Selection dialog appears.

Click Project File… The file to choose is /MyApp/MyAppWeb.war. But it doesnt exist
yet as the packaging has not been run. Instead of selecting it, go in the text field and type
the name of the file /MyApp/MyAppWeb.war. Even if the file doesnt exist, it can be
added to a packaging configuration.
Click OK

Click on OK.
The screen should look like this:

The packaging configuration for the MyApp.ear is now complete.

Click OK to save the packaging configurations.


Right-click on the project and select Run Packaging.

The packaging will display its output in the console. The output in the console will look
like this:
After the execution, you should have a project that looks like this:

3.3 JBoss Configuration and Launch

Now, it is time to configure the JBoss server if it has not been done yet.

Click on the debug shortcut from the top menu and select
Debug to open the debug configurations.

The debug dialog allows you to configure the available JBoss configurations that will be
used for debugging.
Select JBoss 4.0.X in the configurations list. Click New button.
Give a name for the configuration.

Browse to the directory where you have unzipped the JBoss zip file.
After selecting the JBoss home directory, select default from the drop down menu in the
Server Configuration.
In order to view source code when debugging, you must include the project in the source
lookup path; otherwise Eclipse will complain that it cannot locate the source.

To specifiy a source lookup path, go into the JBoss launch configuration and select the
Source tab. Click on the Add button and select Java Project. Select your project and
click OK.

Now Click the Apply button.


Click on Debug and you will see JBoss starting. The output is sent to the console.

INFO [Server] JBoss (MX MicroKernel) [4.0.2 (build: CVSTag=JBoss_4_0_2


date=200505022023)] Started in 51s:77ms

The above line when displayed in the console indicates that the JBoss server has started.
3.4 Deployment

The deployment is fairly simple. Right click on the MyApp.ear file and select the
Deployment > Deploy To item.

A dialog box appears with the list of the deployment targets. It contains both the default
and the user-defined deployment targets.

Select the one you are interested in and click OK

In the console view, you should see some deployment activity. The J2EE application is
now deployed.
The console will look like this:

When a resource is deployed, a small decorator appears in the top-left corner of the icon.

See the MyApp.ear file in the figure above.


Open a web browser and type http://localhost:8080/myapp/. The host/port can change if
the web server listens on another host/port. You should see an html page like the one
below:

Input a positive value(say 20) and click on Compute. The output.jsp file will be
displayed:
4 The Servlet and the Web-App
Let’s now modify the project to capture the size of the Fibonacci series from the user and
compute and display the output using a servlet.

4.1 Creating the JSP and Servlet Files

Create a servlet
Create a servlet to perform the actual computation of the Fibonacci suite.

Create a new HTTP Servlet. Select File > New > Other... and choose JBoss-IDE > Web
Components > HTTP Servlet. Click Next

Configure the servlet as follows

1. Give the Package name as myapp.web.


2. Set the Class Name to ComputeServlet.
3. Under Which method stubs would you like to create?, check the init() method.
4. Under Which service method stubs would like to create?, check the doPost()
method.
5. Click Finish

Edit the code for ComputeServlet to complete the doPost method as shown. The code
will parse the request to get the limit parameter, call the computation method and redirect
to the output page
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException,IOException
{
// TODO Auto-generated method stub
try
{
int limit = 0;
String value = req.getParameter("limit");
if (value != null)
{
try
{
limit = Integer.parseInt(value);
}
catch (Exception e)
{}
}
double[] result = compute(limit);

req.setAttribute("fibSeries",result);
req.setAttribute("limit",value);
RequestDispatcher dispatcher = req.getRequestDispatcher("output.jsp");
dispatcher.forward(req, resp);
}
catch (Exception e)
{
e.printStackTrace();
}
}

Also add the compute method for calculating the Fibonacci series.

public double[] compute(int number) throws Exception


{
if (number < 0)
{
throw new Exception("Argument should be positive");
}

double[] suite = new double[number + 1];


suite[0] = 0;

if (number == 0)
{
return suite;
}
suite[1] = 1;
for (int i = 2; i <= number; i++)
{
suite[i] = suite[i - 1] + suite[i - 2];
}
return suite;
}
Correct and complete the attributes of the tag with the following values (press
CTRL+Space for each attribute if you want the completion):

/**
* Servlet Class
*
* @web.servlet name="Compute"
* display-name="Computation Servlet"
* description="Servlet that compute
Fibonacci suite"
* @web.servlet-mapping url-pattern="/Compute"
*/
public class ComputeServlet extends HttpServlet {

After that, the file should look like this. Now we are ready to run XDoclet on the file,
which will generate the Web descriptors.
package myapp.web;

import javax.servlet.http.HttpServlet;

import javax.servlet.ServletException;
import javax.servlet.ServletConfig;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;

/**
* Servlet Class
*
* @web.servlet name="Compute"
* display-name="Computation Servlet"
* description="Servlet that compute Fibonacci suite"
* @web.servlet-mapping url-pattern="/Compute"
*/
public class ComputeServlet extends HttpServlet {

public ComputeServlet() {
super();
// TODO Auto-generated constructor stub
}

public void init(ServletConfig config) throws ServletException {


super.init(config);
// TODO Auto-generated method stub
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException,IOException
{
// TODO Auto-generated method stub
try
{
int limit = 0;
String value = req.getParameter("limit");
if (value != null)
{
try
{
limit = Integer.parseInt(value);
} catch (Exception e)
{}
}
double[] result = compute(limit);

req.setAttribute("fibSeries",result);
req.setAttribute("limit",value);
RequestDispatcher dispatcher = req.getRequestDispatcher("output.jsp");
dispatcher.forward(req, resp);
}
catch (Exception e)
{
e.printStackTrace();
}
}

public double[] compute(int number) throws Exception


{
if (number < 0)
{
throw new Exception("Argument should be positive");
}

double[] suite = new double[number + 1];


suite[0] = 0;

if (number == 0)
{
return suite;
}
suite[1] = 1;
for (int i = 2; i <= number; i++)
{
suite[i] = suite[i - 1] + suite[i - 2];
}
return suite;
}
}

The index.jsp has to be modified to change the form action to “Compute”


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>
Fibonacci Application
</title>
</head>
<body>
<h1>Fibonacci Form</h1>
<form action="Compute" method="POST" >

Modify the output.jsp file to display the results passed by the servlet

<html>
<head>
<title>
Fibonacci Computation
</title>
</head>
<body>
<h1>
Fibonacci Computation
</h1>
<p>
The first <%= request.getAttribute("limit")%> Fibonacci numbers
<%
double[] result=(double[])request.getAttribute("fibSeries");
for (int i = 0; i < result.length; i++)
{
%>
<br>
<%= i %> : <%= result[i] %>
<%
}
%>
</p>
</body>
</html>

4.2 Generation of the Servlet related files

The WAR and EAR files will now be modified.

• The The Web Application WAR. It will contain the Servlet class, as well as the
web.xml deployment descriptors.
• The J2EE Application EAR. It will contain the Web Application War, as well as
the application.xml deployment descriptor.

To generate the Web descriptors, we need to create an XDoclet configuration. With


JBoss Eclipse IDE, you can define several XDoclet generation configurations that will be
run against the project.

4.2.1 XDoclet Web Configuration Creation

1. Right-click on the project and select Properties.


2. In the properties page, select XDoclet Configurations.
3. At the top of the page there is a check-box labeled Enable XDoclet. Check this
check-box.
4. Right-click in the top area to pop-up the menu and choose Add. Type Web in the
dialog and click OK.

You have created a new generation configuration named Web.


Webdoclet Configuration
1. Select the Web configuration.
2. In the lower-left area, right-click to popup the menu and choose Add Doclet.

3. A list of available doclets will appear. Choose webdoclet and click OK.

4. On the lower-right area, you see the properties of the webdoclet.


a. Set the destDir property to src/WEB-INF.
Our configuration now contains a webdoclet that will produce files in the src/WEB-
INF folder.

Fileset Configuration

1. In the lower-left area, right-click on webdoclet to popup the menu and choose
Add.
2. A list of available subtasks will appear. Choose fileset and click Ok.

3. On the lower-right area, you see the properties of the fileset.


a) Set the dir property to src.
b) Uncheck excludes
c) Set the includes property to **/*Servlet.java.

Deployment Descriptor Configuration

1. Add a new deploymentdescriptor subtask to the webdoclet (see above).


2. Set the Servletspec property to 2.3.

All of the standard Web deployment descriptors will now be placed in the src/WEB-INF
directory (property is inherited from webdoclet).

JBoss Configuration
• Add a new jbosswebxml subtask to the webdoclet (see above).
a) Set the Version property to 3.0.
All of the JBoss-specific Web deployment descriptors will now be placed in the
src/WEB-INF directory (property is inherited from webdoclet).
Click OK and the XDoclet configuration for the MyApp project will be saved.

Once the configuration is saved, right-click on the MyApp project and select Run
XDoclet. The XDoclet generation will display its output in the console. The output
should look like this:

After the generation, you should have a project that looks like this. Note that a WEB-INF
folder has been created with the web deployment descriptors (both standard and jboss).
4.2.2 MyAppWeb.war configuration

Change the packaging configuration of MyApp to include the web.xml and servlet class
files in MyAppWeb.war

1. Right-click on the MyApp project and select Properties.


2. Select the Packaging Configurations property
3. Select the MyAppWeb.war item and right-click in the area to pop-up the menu
and choose Add Folder. A “Folder Selection” dialog appears.
4. Click on Project Folder and select the /MyApp/bin folder from the “Folder
Chooser” dialog.

5. As we only want the Servlet class, set the include filter to myapp/web/*.class.
6. The classes must be located under the WEB-INF/classes of the War package.
Set the prefix to WEB-INF/classes.
7. Click on OK.

To add the standard Web deployment descriptor

1. Select the MyAppWeb.war item and right-click in the area to pop-up the menu
and choose Add File. A File Selection dialog appears.

2. Click Project File.The file to choose is /MyApp/src/WEB-INF/web.xml.


3. The web.xml must be located under the WEB-INF of the War package. Set the
prefix to WEB-INF.

4. Click on OK.
To add the JBoss specific Web deployment descriptor

1. Select the MyAppWeb.war item and right-click in the area to pop-up the menu
and choose Add File. A File Selection dialog appears.
2. The file to choose is /MyApp/src/WEB-INF/jboss-web.xml.

3. The jboss-web.xml must be located under the WEB-INF of the War package.
Set the prefix to WEB-INF.

4. Click on OK.

The packaging configuration for the MyApp.war is now complete.


Click OK.

Right-click on the project and select Run Packaging. The packaging will display its
output in the console. The output should look like this:

After the execution, you should have a project that looks like this:
4.3 Deployment

1. Select the MyApp.ear file and right click.


2. Select the Redeploy option.
Open a web browser and type http://localhost:8080/myapp/. The host/port can change if
the web server listens on another host/port. You should see an html page like the one
below:

Enter a positive value in the field and press Compute.


You will get an output page which displays the first 10 elements of the Fibonacci series
5 The EJB

The next step is to create an EJB.


In the previous application, we’ll move the business method that computes Fibonacci
suite to our EJB from the servlet. For simplicity, it will be a stateless session bean
5.1 Creating the EJB

Create a new Session EJB. Select File > New > Other... and choose JBoss-IDE >
EJB Components > Session Bean.

The package will be myapp.ejb and the class name MyAppBean.

Leave the default options selected and be sure that ejbCreate() method is checked.
Click on Finish. The class is then created and you should have a project like this. Note
that all the method stubs are created with the default ejbCreate method
To create the business method for the Fibonacci series computation:

Right-click the MyAppBean class, under the MyAppBean.java file. You should see a
J2EE menu. Select J2EE > Add Business Method.
In the method wizard, enter compute as the method name, double[] for the return type
and add a parameter(By clicking the Add button) called number of type int.
Click on Finish.

A new method has been added to the MyAppBean class.

In the text editor, complete the body of the compute method as below :
public double[] compute(int number) {
// TODO Auto-generated method stub
if (number < 0) {
throw new EJBException("Argument should be positive");
}

double[] suite = new double[number + 1];


suite[0] = 0;

if (number == 0) {
return suite;
}

suite[1] = 1;

for (int i = 2; i <= number; i++) {


suite[i] = suite[i - 1] + suite[i - 2];
}

return suite;
}
As you may have noticied, each wizard adds all of the required XDoclet tags. Go to the
top of the class and complete the attributes of the tag with the following values (by
pressing CTRL+Space for each attribute, you will get an auto-compled list) :

/**
* @ejb.bean name="MyApp"
* display-name="Name for MyApp"
* description="Description for MyApp"
* jndi-name="ejb/MyApp"
* type="Stateless"
* view-type="remote"
*/

After that, the file should look like this. Now, we are ready to run XDoclet on the file to
generate the EJB interfaces.
package myapp.ejb;

import java.rmi.RemoteException;

import javax.ejb.EJBException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;

import javax.ejb.CreateException;

/**
* @ejb.bean name="MyApp"
* display-name="Name for MyApp"
* description="Description for MyApp"
* jndi-name="ejb/MyApp"
* type="Stateless"
* view-type="remote"
*/
public class MyAppBean implements SessionBean {

public MyAppBean() {
super();
// TODO Auto-generated constructor stub
}

public void setSessionContext(SessionContext ctx)


throws EJBException,
RemoteException {
// TODO Auto-generated method stub

public void ejbRemove() throws EJBException, RemoteException {


// TODO Auto-generated method stub

}
public void ejbActivate() throws EJBException, RemoteException {
// TODO Auto-generated method stub

public void ejbPassivate() throws EJBException, RemoteException {


// TODO Auto-generated method stub

/**
* Default create method
*
* @throws CreateException
* @ejb.create-method
*/
public void ejbCreate() throws CreateException {
// TODO Auto-generated method stub
}

/**
* Business method
* @ejb.interface-method view-type = "remote"
*/
public double[] compute(int number) {
// TODO Auto-generated method stub
if (number < 0) {
throw new EJBException("Argument should be positive");
}

double[] suite = new double[number + 1];


suite[0] = 0;

if (number == 0) {
return suite;
}

suite[1] = 1;

for (int i = 2; i <= number; i++) {


suite[i] = suite[i - 1] + suite[i - 2];
}

return suite;
}
} 5.2 Generation of the EJB related files

5.2.1 XDoclet EJB Configuration Creation

To generate the EJB related classes and descriptors, we need to modify the XDoclet
configurations.

1. Edit the project properties by right clicking on the project and select
Properties.
2. In the property page, select XDoclet configurations.
3. Right-click in the upper area to pop-up the menu and choose Add. Type EJB in
the dialog and click OK.

You have created a new generation configuration named EJB.


Ejbdoclet Configuration

1. Select the EJB configuration.


2. In the lower-left area, right-click to popup the menu and choose Add Doclet.
3. A list of available doclets will appear. Choose ejbdoclet and click OK.
4. On the lower-right area, you see the properties of the ejbdoclet.
a. Set the destDir property to src.
b. Set the ejbSpec property to 2.0.

Our configuration now contains an ejbdoclet that will produce files in src folder and
for the EJB 2.0 specifications.
Fileset Configuration

1. In the lower-left area, right-click on ejbdoclet to popup the menu and choose
Add.
2. A list of available subtasks will appear. Choose fileset and click Ok.
3. On the lower-right area, you see the properties of the fileset.
a. Set the dir property to src.
b. Uncheck excludes
c. Set the includes property to **/*Bean.java.

Our configuration now contains an ejbdoclet with a fileset that contains the src
directory, and all files under it that end in Bean.java.
Deployment Descriptor Configuration

• Add a new deploymentdescriptor subtask to the ejbdoclet (see above).


a. Set the destDir property to src/META-INF.

All of the standard EJB deployment descriptors will now be placed in the src/META-
INF directory.
JBoss Configuration

• Add a new jboss subtask to the ejbdoclet (see above).


a. Set the destDir property to src/META-INF.
b. Set the Version property to 3.0.

All of the JBoss-specific deployment descriptors will now be placed in the src/META-
INF directory.
Package Substitution Configuration

• Add a new packageSubstitution subtask to the ejbdoclet (see above).


a. Set the packages property to ejb.
b. Set the substituteWith property to interfaces.

This will place our generated EJB interfaces in the myapp.interfaces java package.
Interface Configuration

1. Add a new remoteInterface subtask to the ejbdoclet (see above).


2. Add a new homeInterface subtask to the ejbdoclet (see above).

These subtasks will generate the EJB home and remote interfaces.
Click OK and the XDoclet configuration for the MyApp project will be saved.
Once the configuration is saved, right-click on the MyApp project and select Run
XDoclet. The XDoclet generation will display its output in the console. The output
should look like this:
After the code generation, select the project and refresh it (you can press F5). You should
have a project that looks like this. Note that a myapp.interfaces package has been
created with new classes inside. META-INF folder now conatins the deployment
descriptors (both standard and jboss) also.

5.3 Modifying the servlet

ComputeServlet has to be modified to this EJB to perform the actual computation of the
Fibonacci suite.

Our servlet needs some initialization and processing code. Add the following private
member.

private MyAppHome home;


Complete the init method as shown. This code is responsible for the initialization of the
EJB Home interface and grabbing the local environment entry.

public void init(ServletConfig config) throws ServletException {


try
{
Context context = new InitialContext();
Object ref = context.lookup("java:/comp/env/ejb/MyApp");
home = (MyAppHome) PortableRemoteObject.narrow(ref, MyAppHome.class);
}
catch (Exception e)
{
throw new ServletException("Lookup of java:/comp/env/ failed");
}
}
}

Complete the doPost method as shown. The code will parse the request to get the limit
parameter, create an instance of the EJB, perform computation, release the instance and
redirect to the output page.
pprotected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException,IOException
{
// TODO Auto-generated method stub
try
{
MyApp bean = home.create();
int limit = 0;
String value = req.getParameter("limit");
if (value != null) {
try {
limit = Integer.parseInt(value);
} catch (Exception e) {
}
}
double[] result = bean.compute(limit);
bean.remove();

req.setAttribute("fibSeries",result);
req.setAttribute("limit",value);
RequestDispatcher dispatcher = req.getRequestDispatcher("output.jsp");
dispatcher.forward(req, resp);
}
catch (Exception e)
{
e.printStackTrace();
}
The compute method can now be deleted from the servlet as it has been moved to the
}
EJB.

The compute method can be removed from the servlet as this logic is now in the bean.
Next, we will insert the missing XDoclet tags for the Servlet. In the Java editor go in the
Javadoc class paragraph. Type web. And press CTRL+Space. You should see JBoss
Eclipse IDE's auto-completion in action.

Correct and complete the attributes of the tag with the following values (press
CTRL+Space for each attribute if you want the completion) :
/**
* Servlet Class
*
* @web.servlet name="Compute"
* display-name="Computation Servlet"
* description="Servlet that compute Fibonacci suite"
* @web.servlet-mapping url-pattern="/Compute"
* @web.ejb-ref
* name="ejb/MyApp"
* type="Session"
* home="myapp.interfaces.MyAppHome"
* remote="myapp.interfaces.MyApp"
* description="Reference to the MyApp EJB"
*
* @jboss.ejb-ref-jndi
* ref-name="ejb/MyApp"
* jndi-name="ejb/MyApp"
*/
public class ComputeServlet extends HttpServlet {

After that, the file should look like this. Now we are ready to run XDoclet on the file,
which will generate the Web descriptors.
package myapp.web;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;
import javax.servlet.http.HttpServlet;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletConfig;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import myapp.interfaces.MyApp;
import myapp.interfaces.MyAppHome;
/**
* Servlet Class
*
* @web.servlet name="Compute"
* display-name="Computation Servlet"
* description="Servlet that compute Fibonacci suite"
* @web.servlet-mapping url-pattern="/Compute"
* @web.ejb-ref
* name="ejb/MyApp"
* type="Session"
* home="myapp.interfaces.MyAppHome"
* remote=" myapp.interfaces.MyApp"
* description="Reference to the MyApp EJB"
*
* @jboss.ejb-ref-jndi
* ref-name="ejb/MyApp"
* jndi-name="ejb/MyApp"
*/
public class ComputeServlet extends HttpServlet {

private MyAppHome home;


public ComputeServlet() {
super();
// TODO Auto-generated constructor stub
}

public void init(ServletConfig config) throws ServletException {


try
{
Context context = new InitialContext();
Object ref = context.lookup("java:/comp/env/ejb/MyApp");
home = (MyAppHome) PortableRemoteObject.narrow(ref, MyAppHome.class);
}
catch (Exception e)
{
throw new ServletException("Lookup of java:/comp/env/ failed");
}
}

protected void doPost(HttpServletRequest req, HttpServletResponse resp)


throws ServletException,
IOException {
// TODO Auto-generated method stub
try
{
MyApp bean = home.create();
int limit = 0;
String value = req.getParameter("limit");
if (value != null) {
try {
limit = Integer.parseInt(value);
} catch (Exception e) {
}
}
double[] result = bean.compute(limit);
bean.remove();
req.setAttribute("fibSeries",result);
req.setAttribute("limit",value);
RequestDispatcher dispatcher =
req.getRequestDispatcher("output.jsp");
dispatcher.forward(req, resp);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

5.4 The Packaging

For deploying this application, three packaging configurations are needed.

• The EJB JAR. It will contain the EJB classes and interfaces, as well as the ejb-
jar.xml and jboss.xml deployment descriptors.
• The Web Application WAR. It will contain the Servlet class as well as the
web.xml deployment descriptors.
• The J2EE Application EAR. It will contain the EJB Jar and the Web Application
War, as well as the application.xml deployment descriptor.

When launched, these three packaging configurations will create the J2EE application
ready to be deployed.

5.4.1 MyAppEJB.jar creation

• Edit the project properties by right clicking on the project and select
Properties.
• In the property page, select Packaging Configurations.
• Right-click in the area to pop-up the menu and choose Add Archive. Type
MyAppEJB.jar in the dialog and click OK.
• You have created a new packaging configuration that will produce the
MyAppEJB.jar file.
We want to add the EJB classes and interfaces. Eclipse has generated the compiled
classes into the bin folder (declared as the default output dir of the project).Select the
MyAppEJB.jar item and right-click in the area to pop-up the menu and choose Add
Folder. A Folder Selection dialog appears.
Select the /MyApp/bin folder and click OK.

The folder is now /MyApp/bin.

As we only want the EJB classes and interfaces, specify the following as an include filter:

myapp/ejb/*.class,myapp/interfaces/*.class

Click on OK
We now want to add the standard EJB deployment descriptor.

Select the MyAppEJB.jar item and right-click in the area to pop-up the menu and
choose Add File. A File Selection dialog appears.

Click on Project File. A File Chooser dialog appears.

Select the /MyApp/src/META-INF/ejb-jar.xml folder and click OK.


The file is now /MyApp/src/META-INF/ejb-jar.xml.

The ejb-jar.xml must be located under the META-INF directory of the EJB package.
Set the prefix to META-INF.

Click on OK.

To add the specific EJB deployment descriptor, select the MyAppEJB.jar item and
right-click in the area to pop-up the menu and choose Add File.

The file to choose is /MyApp/src/META-INF/jboss.xml.


The jboss.xml must be located under the META-INF directory of the EJB package. Set
the prefix to META-INF.

Click on OK.

The packaging configuration for the MyAppEJB.jar is now complete.


Since the packaging happens in the order mentioned in this packaging configuration,
MyAppEJB.jar has to be moved up. Otherwise this jar will not be included in
MyApp.ear.
For doing this select the MyAppEJB.jar and move it up in the configuration by
repeatedly clicking on the Up button.
Finally the configuration looks like this:

5.4.2 Modify MyApp.ear configuration

To add the EJB module, select the MyApp.ear item and right-click in the area to pop-up
the menu and choose Add File. A File Selection dialog appears.

The file to choose is /MyApp/MyAppEJB.jar. But it doesn’t exist yet as the packaging
has not been run. Instead of selecting it, go in the text field and type the name of the file
/MyApp/MyAppEJB.jar. Even if the file doesn’t exist, it can be added to a packaging
configuration.

Click on OK.
Click on OK.

The packaging configuration for the MyApp.ear is now complete.

Click OK to save the packaging configurations.


5.4.3 Modifying application.xml

The application.xml file has to be modified to include the EJB module so that it finally
looks like this:

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


<!DOCTYPE application PUBLIC
"-//Sun Microsystems, Inc.//DTD J2EE Application 1.3//EN"
"http://java.sun.com/dtd/application_1_3.dtd">
<application>
<display-name></display-name>
<module>
<ejb>MyAppEJB.jar</ejb>
</module>
<module>
<web>
<web-uri>MyAppWeb.war</web-uri>
<context-root>/myapp</context-root>
</web>
</module>
</application>

Right-click on the project and select Run Packaging. The packaging will display its
output in the console. The output should look like this:

After the execution, you should have a project that looks like this:
5.5 Deployment

Select MyApp.ear, right click and select the Redeploy option.

Open a web browser and type http://localhost:8080/myapp/. The host/port can change if
the web server listens on another host/port. You should see an html page like the one
below:
Enter a positive value in the field and press Compute.

You will get an output page which displays the first 15 elements of the Fibonacci series
6 JDBC Project

6.1 JDBC Programming

Lets write a simple java program to establish JDBC connectivity with an existing Oracle
database and retrieve data.

6.1.1 The Project

Create a Java project called OracleTest


File> New > Project

Click Next and give the project name as OracleTest


Click Finish. The java project will now be visible in the Package Explorer.

6.1.2 Creating the Java class

Create a new class for this project


Select File >New > Class
Give the package name as myapp and class name as TestOracle
Click Finish.

Complete TestOracle with the following code


package myapp;

import java.sql.*;

public class TestOracle {


static String url = "jdbc:oracle:thin://172.31.15.30/temp";
static String uname = "littlemike";
static String upass = "bigmike";

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

try {
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("Successfully connected");
}catch(Exception e){
System.out.println(e);
}
try{
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@172.31.15.30:1521:ORCL",
"littlemike", "bigmike");
System.out.println("Able to connect to database");
String query = "select name from student";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while(rs.next()){
String name = rs.getString("name");
System.out.println(name);
}
con.close();

}catch(SQLException sqle){
System.out.println(sqle);
}
}
}

Save the class.

6.1.3 Setting Project properties

Goto project properties


Select the Java Build Path property.
Click Add External Jars. Browse and select the ojdbc14.jar

Click OK.

6.1.4 Running the Project

Click on the Run shortcut from the top menu to run the TestOracle class
The output of the code will appear in the console

6.2 JDBC Connection from Eclipse

Notes:
In our example:
1. the database is running on ip address 172.31.15.30
2. the database server name is ORCL
3. the database user name is “littlemike”
4. the database user password is “bigmike”
5. the database name is “temp”.
You may have check with your SYSADMIN for your configuration details before
starting the tutorial and replace them with your configuration where ever it comes.

6.2.1 The Database Explorer

Step 1:

Select Windows->Show View->Other. In the Show View dialog box select Data-
>Database explorer.
6.2.2 Creating a new connection

Step 1:
This will open a Database Explorer View at the bottom among other views like console
view. Right click the view and select new connection.

Step 2:

It will open New Connection Wizard. Select Oracle database and give the details as
shown. You need to have ojdbc14.jar file in your local file system. Give the location of
the class in “Class Location” text box.
Note that Driver class is: oracle.jdbc.driver.OracleDriver
The connection url is: jdbc:oracle:thin:@172.31.15.30:1521:ORCL

Step 3:

Test your connection by clicking test. If everything is correct, it will show “connection
successful” dialog box.
Now at the bottom window, below connection, you can see your database.

6.2.3 Creating SQL Scrapbook

Step 1:

On the right side of the view, we see an icon (marked green). This is SQL scarp book.
By clicking that you can create a new scrape book under your project.
Now the editor will open. And you can try your sql commands in the editor.
Step 2:

Type the sql command you want, and select it and right click. In the pop up window, at
the bottom, you will see run sql. Select that.
Now the result will be shown in the Data Output view.

You can use this environment for creating tables, inserting, updating and all other SQL
activities.
7 Conclusion
This simple tutorial was intended to give an overview of what is possible with JBoss
Eclipse IDE. We hope that it will be useful for developers who want to develop for JBoss
in Eclipse.

Vous aimerez peut-être aussi