Struts Ejb Tutorial
Struts Ejb Tutorial
In this tutorial, you will create a CMP based payment voucher web application by using Struts and EJB.
You will learn how to create a Container Managed Entity Bean to store the voucher. A Session bean will
be used to interact with the CMP. A Model-View-Controller architecture known as Struts will serve as
the front end. The Web portion of this tutorial was adapted from the Building a CMP Based School
Schedule Web Application tutorial by Jason Sholl.
2. JDK 1.4.2
Sun's JDK is available from http://java.sun.com/j2se/1.4.2/download.html
3. JBoss 3.2.3
JBoss is available from http://www.jboss.org/products/jbossas/downloads
4. XDoclet 1.2.3
XDoclet is available from http://xdoclet.sourceforge.net/xdoclet/install.html
3. Select Add.... The Add JRE dialog will open. Name the runtime Sun JDK 1.4.2. Select Browser
for the JRE home directory and choose the location where you installed the JDK 1.4.2. And then
click OK.
4. The Sun JDK 1.4.2 now shows on the list of installed runtimes.
5. Select Server -> Installed Runtimes from the menu on the left.
6. Click on Add.... Select JBoss -> JBoss v3.2.3 and click Next. Click Browse and select the
location where you installed JBoss and click Finish.
7. Check JBoss v3.2.3.
8. Select XDoclet. Make sure the builder item is enabled. Click on the Browse... button and choose
the directory where you have installed XDoclet. Make sure that you choose the correct version.
Click Apply.
9. Select XDoclet -> ejbdoclet. Check JBoss. Click Edit... button to make sure JBoss version is 3.2.
Click Apply.
10. Select XDoclet -> webdoclet. Check JBoss. Click Edit... button to make sure JBoss version is
3.2. Click Apply.
11. Click OK to close the preferences dialog. JDK, XDoclet and JBoss are now configured in
Eclipse.
/**
* Bean implementation class for Entity Bean: PaymentVoucherItem
*
* @ejb.bean name="PaymentVoucherItem" type="CMP" cmp-version="2.x"
* schema="PaymentVoucherItem"
* local-jndi-name="ejb/ejbs/PaymentVoucherItemLocalHome"
* view-type="local" reentrant="true" primkey-field="id"
*
* @ejb.home local-class="ejbs.PaymentVoucherItemLocalHome"
*
* @ejb.interface local-class="ejbs.PaymentVoucherItemLocal"
*
* @ejb.pk class="java.lang.Integer"
*/
4. Now add the necessary getters/setters and XDoclet tags for the primary key.
/**
* @ejb.persistence read-only="false"
* @ejb.interface-method view-type="local"
*/
public abstract Integer getId();
/**
* @ejb.persistence
*/
public abstract void setId(Integer id);
5. At this point, if you save PaymentVoucherItemBean, the XDoclet builder should run cleanly.
6. Now, to add a few more CMP attributes to PaymentVoucherItem bean, add getters/setters and
XDoclet tags.
/**
* @ejb.persistence read-only="false"
* @ejb.interface-method view-type="local"
*/
public abstract String getType();
/**
* @ejb.persistence
* @ejb.interface-method view-type="local"
*/
public abstract void setType(String type);
/**
* @ejb.persistence read-only="false"
* @ejb.interface-method view-type="local"
*/
public abstract String getCode();
/**
* @ejb.persistence
* @ejb.interface-method view-type="local"
*/
public abstract void setCode(String code);
/**
* @ejb.persistence read-only="false"
* @ejb.interface-method view-type="local"
*/
public abstract String getDescription();
/**
* @ejb.persistence
* @ejb.interface-method view-type="local"
*/
public abstract void setDescription(String description);
/**
* @ejb.persistence read-only="false"
* @ejb.interface-method view-type="local"
*/
public abstract float getAmount();
/**
* @ejb.persistence
* @ejb.interface-method view-type="local"
*/
public abstract void setAmount(float amount);
/**
* @ejb.persistence read-only="false"
* @ejb.interface-method view-type="local"
*/
public abstract String getName();
/**
* @ejb.persistence
* @ejb.interface-method view-type="local"
*/
public abstract void setName(String name);
/**
* @ejb.persistence read-only="false"
* @ejb.interface-method view-type="local"
*/
public abstract String getIc();
/**
* @ejb.persistence
* @ejb.interface-method view-type="local"
*/
public abstract void setIc(String ic);
/**
* @ejb.persistence read-only="false"
* @ejb.interface-method view-type="local"
*/
public abstract String getPaymentType();
/**
* @ejb.persistence
* @ejb.interface-method view-type="local"
*/
public abstract void setPaymentType(String paymentType);
7. Next is to add a means by which to create PaymentVoucherItemBean. The create method will
take the Name for the new PaymentVoucherItem and autogenerate a new key. The rudimentary
key generation code is for example purposes only. After you paste the code below, do an
organized imports (Control-Shift-o) to add an import for CreateException.
/**
* ejbCreate
*
* @ejb.create-method view-type="local"
*/
public Integer ejbCreate(String name) throws CreateException {
setId(new Integer(PRIMKEY++));
setName(name);
return null;
}
/**
* ejbPostCreate
*/
public void ejbPostCreate(String name) throws CreateException {
}
8. The last step is to add a few finder definitions. These should be added to the class level javadoc
(right below @ejb.pk class definition added before).
9. At this point if you save and build, you should be able to open PaymentVoucherItemLocal and
PaymentVoucherItemLocalHome and see all method stubs were appropriately generated. Do not
edit these files. Once you are done inspecting them, close them both.
/**
* @ejb.interface-method view-type="both"
*/
public PaymentVoucherItemWrapper addPaymentVoucherItem(String type,
String code, String description, float amount, String name,
String ic, String paymentType) {
PaymentVoucherItemLocalHome home = getPaymentVoucherItemLocalHome();
try {
PaymentVoucherItemLocal paymentVoucherItem = home.create(name);
paymentVoucherItem.setType(type);
paymentVoucherItem.setCode(code);
paymentVoucherItem.setDescription(description);
paymentVoucherItem.setAmount(amount);
paymentVoucherItem.setIc(ic);
paymentVoucherItem.setPaymentType(paymentType);
return new PaymentVoucherItemWrapper(type, code, description,
amount, name, ic, paymentType);
} catch (CreateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* @ejb.interface-method view-type="both"
*/
public PaymentVoucherItemWrapper editPaymentVoucherItemForId(Integer id,
String type,
String code, String description, float amount, String name,
String ic, String paymentType) {
PaymentVoucherItemLocalHome home = getPaymentVoucherItemLocalHome();
try {
PaymentVoucherItemLocal paymentVoucherItem =
home.findByPrimaryKey(id);
paymentVoucherItem.setType(type);
paymentVoucherItem.setCode(code);
paymentVoucherItem.setDescription(description);
paymentVoucherItem.setAmount(amount);
paymentVoucherItem.setIc(ic);
paymentVoucherItem.setPaymentType(paymentType);
return new PaymentVoucherItemWrapper(id, type, code, description,
amount, name, ic, paymentType);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* @ejb.interface-method view-type="both"
*/
public List getPaymentVoucherItem(String name) {
PaymentVoucherItemLocalHome home = getPaymentVoucherItemLocalHome();
try {
Collection items = home.findByName(name);
return wrapPaymentVoucherItemsInList(items);
} catch (FinderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* @ejb.interface-method view-type="both"
*/
public List getAllPaymentVoucherItems() {
PaymentVoucherItemLocalHome home = getPaymentVoucherItemLocalHome();
try {
Collection items = home.findAll();
return wrapPaymentVoucherItemsInList(items);
} catch (FinderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* @ejb.interface-method view-type="both"
*/
public List getPaymentVoucherItemsForIc(String ic) {
PaymentVoucherItemLocalHome home = getPaymentVoucherItemLocalHome();
try {
Collection items = home.findByIc(ic);
return wrapPaymentVoucherItemsInList(items);
} catch (FinderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* @ejb.interface-method view-type="both"
*/
public List getPaymentVoucherItemsForId(Integer id) {
PaymentVoucherItemLocalHome home = getPaymentVoucherItemLocalHome();
try {
Collection items = (Collection) home.findByPrimaryKey(id);
return wrapPaymentVoucherItemsInList(items);
} catch (FinderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* @ejb.interface-method view-type="both"
*/
public void removePaymentVoucherItemsForId(Integer id) {
PaymentVoucherItemLocalHome home = getPaymentVoucherItemLocalHome();
try {
home.findByPrimaryKey(id).remove();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @ejb.interface-method view-type="both"
*/
public void editPaymentVoucherItemsForId(Integer id, String type,
String code, String description, float amount, String name,
String ic, String paymentType) {
PaymentVoucherItemLocalHome home = getPaymentVoucherItemLocalHome();
try {
home.findByPrimaryKey(id).setType(type);
home.findByPrimaryKey(id).setCode(code);
home.findByPrimaryKey(id).setDescription(description);
home.findByPrimaryKey(id).setAmount(amount);
home.findByPrimaryKey(id).setName(name);
home.findByPrimaryKey(id).setIc(ic);
home.findByPrimaryKey(id).setPaymentType(paymentType);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
5. Right click on PaymentVoucherItemWrapper in the source editor and select Source -> Generate
Getters and Setters. Generate a getter and setter for each field.
6. Finally, add the following constructor.
2. Click Browse... and select the location where you downloaded the WAR file, fill in
'StrutsPaymentVoucher' for the Web project name and select 'JBoss v3.2.3' for target runtime,
check 'Add module to an EAR application' and fill in 'PaymentVoucherEAR' for the EAR
Application name. Click finish.
3. Expand the 'Dynamic Web Projects' node in the project explorer, and right click on
StrutsPaymentVoucher and select 'Properties'.
4. Select the 'J2EE Module Dependencies' properties page, and then click the checkbox next to
'PaymentVoucherEJB.jar' to add a module dependency to the EJB module.
Creating struts-config.xml file
A Struts application has to have a Struts application configuration file. In this example and in most other
simple Struts applications, the default name of the configuration file is struts-config.xml and it typically
resides under application's ./WEB-INF directory. The configuration information is then read by Struts
framework when the application gets started.
1. Open struts-config.xml in Text Editor if it is not open.
2. Add the following XML tags to define form bean definition and action mapping definition.
<action path="/edit"
type="submit.EditAction"
name="SubmitForm"
input="/edit.jsp"
scope="request"
validate="true">
<forward name="edit" path="/edit.jsp"/>
<forward name="afterUpdate" path="/print.jsp"/>
<forward name="index" path="/index.jsp"/>
</action>
</action-mappings>
package submit;
import org.apache.struts.validator.ValidatorForm;
package submit;
import javax.ejb.CreateException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import ejbs.PaymentVoucherSessionLocal;
import ejbs.PaymentVoucherSessionLocalHome;
/**
* @web.ejb-local-ref home="ejbs.PaymentVoucherSessionLocalHome"
* local="ejbs.PaymentVoucherSessionLocal"
* name="ejb/PaymentVoucherSession" type="Session"
* link="PaymentVoucherSession"
*
* @jboss.ejb-local-ref ref-name="PaymentVoucherSession"
* jndi-name="ejb/ejbs/PaymentVoucherSessionHome"
*
*/
try {
PaymentVoucherSessionLocal paymentVoucherSession =
getPaymentVoucherSession();
String operation = request.getParameter("operation");
if (operation.equals("add")) {
// Cast ActionForm object to SubmitForm type
SubmitForm f = (SubmitForm) form;
paymentVoucherSession.addPaymentVoucherItem(type,
code,
description, amount, name, ic,
paymentType);
request.getSession().setAttribute("items",
paymentVoucherSession.getAllPaymentVoucherItems());
request.getSession().setAttribute("title",
"<p><b>:: PAYMENT VOUCHER ADDED
SUCCESSFULLY ::</b></p>");
return (mapping.findForward("afterAdd"));
}
else if (operation.equals("name")) {
String name = request.getParameter("searchName");
request.getSession().setAttribute("title",
"<p><b>:: NAME MATCHING " + name +
"::</b></p>");
request.getSession().setAttribute("items",
paymentVoucherSession.getPaymentVoucherItem(name));
return (mapping.findForward("printResults"));
}
else if (operation.equals("ic")) {
String ic = request.getParameter("searchIC");
request.getSession().setAttribute("title",
"<p><b>:: IC MATCHING " + ic +
"::</b></p>");
request.getSession().setAttribute("items",
paymentVoucherSession.getPaymentVoucherItemsForIc(ic));
return (mapping.findForward("printResults"));
}
else if (operation.equals("list")) {
request.getSession().setAttribute("items",
paymentVoucherSession.getAllPaymentVoucherItems());
request.getSession().setAttribute("title",
"<p><b>:: ALL PAYMENT VOUCHERS
::</b></p>");
return (mapping.findForward("printResults"));
}
else if (operation.equals("edit")) {
return (mapping.findForward("edit"));
}
else if (operation.equals("update")) {
paymentVoucherSession.editPaymentVoucherItemsForId(
new Integer(request.getParameter("id")),
request.getParameter("type"),
request.getParameter("code"),
request.getParameter("description"),
Float.parseFloat(request.getParameter("amount")),
request.getParameter("name"),
request.getParameter("ic"),
request.getParameter("paymentType"));
request.getSession().setAttribute("items",
paymentVoucherSession.getAllPaymentVoucherItems());
request.getSession().setAttribute("title",
"<p><b>:: PAYMENT VOUCHER UPDATED
SUCCESSFULLY ::</b></p>");
return (mapping.findForward("afterUpdate"));
}
else if (operation.equals("delete")) {
paymentVoucherSession.removePaymentVoucherItemsForId(
new Integer(request.getParameter("id")));
return (mapping.findForward("afterDelete"));
}
else if (operation.equals("index")) {
return (mapping.findForward("index"));
}
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
try {
return paymentVoucherSessionLocalHome.create();
}
catch (CreateException e) {
e.printStackTrace();
}
return null;
}
}
4. Next, create another new class file. Select File -> New -> Other -> Java -> Class and then click
Next.
5. Fill in 'submit' for the package, and 'EditAction' for the class name and then click Finish.
6. Open EditAction in the Java editor and add the following code to provide business logic of your
application.
package submit;
import javax.ejb.CreateException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import ejbs.PaymentVoucherSessionLocal;
import ejbs.PaymentVoucherSessionLocalHome;
/**
* @web.ejb-local-ref home="ejbs.PaymentVoucherSessionLocalHome"
* local="ejbs.PaymentVoucherSessionLocal"
* name="ejb/PaymentVoucherSession" type="Session"
* link="PaymentVoucherSession"
*
* @jboss.ejb-local-ref ref-name="PaymentVoucherSession"
* jndi-name="ejb/ejbs/PaymentVoucherSessionHome"
*
*/
try {
PaymentVoucherSessionLocal paymentVoucherSession =
getPaymentVoucherSession();
String operation = request.getParameter("operation");
if (operation.equals("edit")) {
return (mapping.findForward("edit"));
}
else if (operation.equals("update")) {
paymentVoucherSession.editPaymentVoucherItemsForId(
new Integer(request.getParameter("id")),
request.getParameter("type"),
request.getParameter("code"),
request.getParameter("description"),
Float.parseFloat(request.getParameter("amount")),
request.getParameter("name"),
request.getParameter("ic"),
request.getParameter("paymentType"));
request.getSession().setAttribute("items",
paymentVoucherSession.getAllPaymentVoucherItems());
request.getSession().setAttribute("title",
"<p><b>:: PAYMENT VOUCHER UPDATED
SUCCESSFULLY ::</b></p>");
return (mapping.findForward("afterUpdate"));
}
else if (operation.equals("index")) {
return (mapping.findForward("index"));
}
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
if (null == paymentVoucherSessionLocalHome) {
try {
Context context = new InitialContext();
Object obj = context
.
lookup("java:comp/env/ejb/PaymentVoucherSession");
paymentVoucherSessionLocalHome =
(PaymentVoucherSessionLocalHome) PortableRemoteObject
.narrow(obj,
PaymentVoucherSessionLocalHome.class);
}
catch (NamingException e) {
e.printStackTrace();
}
}
try {
return paymentVoucherSessionLocalHome.create();
}
catch (CreateException e) {
e.printStackTrace();
}
return null;
}
}
Creating A JSP
This is the final piece of this example payment voucher application, and you are going to use Struts tags
to provide a user interface. In this sample application, you need to create three JSP pages.
1. Select File -> New -> Other -> Web -> JSP and click next to create a new JSP page.
2. Select the WebContent directory under StrutsPaymentVoucher, and fill in index.jsp for the file
name. Click finish.
3. Open index.jsp in the JSP editor and add the following code.
<html>
<head>
<title>Payment Voucher</title>
</head>
<body>
<html:errors/>
<html:form action="list.do">
<table>
<html:hidden property="operation" value="add"/>
<tr><td><b><u>Payment Vouchers</u></b></td><td></td></tr>
<tr><td>Type: </td><td><html:text property="type"/></td></tr>
<tr><td>Code: </td><td><html:text property="code"/></td></tr>
<tr><td>Description: </td><td><html:text property="description"/></td></tr>
<tr><td>Amount: </td><td><html:text property="amount"/></td></tr>
<tr><td>Name: </td><td><html:text property="name"/></td></tr>
<tr><td>IC: </td><td><html:text property="ic"/></td></tr>
<tr><td>Payment Type: </td><td><html:radio property="paymentType"
value="Cash"/>Cash
<html:radio property="paymentType" value="Cheque"/>Cheque</td></tr>
</table>
<hr>
<html:form action="list.do">
<html:hidden property="operation" value="name"/>
<table>
<tr><td>Name: </td><td><html:text property="searchName"/></td></tr>
</table>
<html:submit value="Find Payment Vouchers By Name"/>
</html:form>
<hr>
<html:form action="list.do">
<html:hidden property="operation" value="ic"/>
<table>
<tr><td>IC: </td><td><html:text property="searchIC"/></td></tr>
</table>
<html:submit value="Find Payment Vouchers By IC"/>
</html:form>
<hr>
<html:form action="list.do">
<html:hidden property="operation" value="list"/>
<html:submit value="List All Payment Vouchers"/>
</html:form>
</body>
</html>
4. After that, you need to create another JSP page and fill in 'edit.jsp' for the JSP name. And then
click finish.
5. Open the edit.jsp in the JSP editor and add the following code.
<html>
<head>
<title>Payment Voucher</title>
</head>
<body>
<html:errors/>
<html:form action="edit.do">
<table>
<html:hidden property="operation" value="update"/>
<html:hidden property="id" value="<%=request.getParameter("id")%>"/>
<tr><td><b><u>Payment Vouchers</u></b></td><td></td></tr>
<tr><td>Type: </td><td><html:text property="type"/></td></tr>
<tr><td>Code: </td><td><html:text property="code"/></td></tr>
<tr><td>Description: </td><td><html:text property="description"/></td></tr>
<tr><td>Amount: </td><td><html:text property="amount"/></td></tr>
<tr><td>Name: </td><td><html:text property="name"/></td></tr>
<tr><td>IC: </td><td><html:text property="ic"/></td></tr>
<tr><td>Payment Type: </td><td><html:radio property="paymentType"
value="Cash"/>Cash
<html:radio property="paymentType" value="Cheque"/>Cheque</td></tr>
</table>
<html:form action="edit.do">
<html:hidden property="operation" value="index"/>
<html:submit value="Abort"/>
</html:form>
</body>
</html>
6. Create a JSP page again and fill in 'print.jsp' for the JSP name. And then add the following code.
<html>
<head>
<title>Payment Voucher</title>
</head>
<body>
<%= request.getSession().getAttribute("title")%>
<% List items= (List) request.getSession().getAttribute("items");%>
<%
for (int i = 0; i < items.size(); i++) {
PaymentVoucherItemWrapper item = (PaymentVoucherItemWrapper)
items.get(i);
%>
<tr>
<td><a href="edit.do?operation=edit&id=<%=item.getId()%>
&type=<%=item.getType()%>
&code=<%=item.getCode()%>
&description=<%=item.getDescription()%>
&amount=<%=item.getAmount()%>
&name=<%=item.getName()%>
&ic=<%=item.getIc()%>
&paymentType=<%=item.getPaymentType()%>">Edit</a></td>
<td><a
href="list.do?operation=delete&id=<%=item.getId()%>">Delete</a></td>
<td><%= item.getType() %></td>
<td><%= item.getCode() %></td>
<td><%= item.getDescription() %></td>
<td><%= item.getAmount() %></td>
<td><%= item.getName() %></td>
<td><%= item.getIc() %></td>
<td><%= item.getPaymentType() %></td>
</tr>
<% }
%>
</table>
<br>
<html:form action="list.do">
<html:hidden property="operation" value="index"/>
<html:submit value="Return"/>
</html:form>
</body>
</html>
4. Right click on the new server and select 'Add and Remove Projects...' which will bring up the
dialog below.
5. Select PaymentVoucherEAR from the left panel and click 'Add >' to add it to the right panel as
shown below. Click Finish.
6. Right click on the newly created server in the Servers view and select Start. Wait a few seconds
to ensure the server started up correctly. The Console view should look something like this:
7. Now, back in the Project Explorer right click on 'index.jsp' and select 'Run As' -> 'Run on
Server'.
8. This will bring up the below dialog. Select JBOSS 3.2.3 and check 'Set server as project
default(do not ask again)' and click Finish.
9. An embedded web browser should open showing the following page.
10. You can experiment by adding more records into your payment voucher.
Summary
In this tutorial you learned how to configure Eclipse to work with JBoss and create J2EE EJB and Struts
projects that uses a CMP Bean, a Session Bean, an ActionForm class, an Action class, and a JSP to
create a payment voucher J2EE Web application. This application, while simple, provides a good
introduction to Java Web development and some of the Web development tools available in the Eclipse
Web Tools Platform project.