Struts-ejb-tutorial

  • July 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Struts-ejb-tutorial as PDF for free.

More details

  • Words: 4,202
  • Pages: 65
Building a CMP Based Payment Voucher Web Application By Using Struts and EJB 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. Prerequisites For The Tutorial 1. Web Tools Platform (WTP) project The WTP project can be downloaded from http://download.eclipse.org/webtools/downloads/ 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 Installing The JBoss and XDoclet Runtimes In Eclipse In order to run the EJB and Web modules from Eclipse (which will allow you to test and debug the modules), Eclipse has to be told where to find JBoss, XDoclet and where to find the JDK. JBoss requires a JDK so it can compile java class and JSPs. 1. Select Window -> Preferences.

2. Select Java -> Installed JREs from the menu on the left.

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. Creating An EJB Project The first step is to create an EJB project for the EJB module. 1. Select File -> New -> Project -> EJB -> EJB Project.

2. Click Next and fill in 'PaymentVoucherEJB' for the EJB project name, check 'Add project to an EAR' and fill in 'PaymentVoucherEAR' for the EAR Application name, click Next.

3. Click Next again and uncheck EJB client JAR support, and click Finish.

4. Once the wizard finishes, switch to the J2EE Perspective and see your newly created EJB Project.

Creating An EJB Session Bean Now you will create a Session bean in the PaymentVoucherEJB EJB project. 1. Select File -> New -> Other -> EJB -> XDoclet Enterprise JavaBean.

2. Click Next and check 'SessionBean'.

3. Click Next, fill in 'ejbs' for the package and 'PaymentVoucherSessionBean' for the class name.

4. Click finish to create your Session bean and see it in the Project Explorer. The annotations builder should have run and generated local and remote, and local and remote home interfaces.

It is important to remember when developing EJBs using Xdoclet to only edit the actual bean classes (e.g. ejbs.PaymentVoucherSessionBean). All deployment descriptor metadata, as well as the various EJB interfaces are generated using the XDoclet javadoc tags. If you open PaymentVoucherSessionBean, you can see some of these tags. Full documentation on how to use these tags can be found in the XDoclet docs. Creating A CMP Bean At the time of this writing, there is no tooling support Entity beans. Entity beans may be created, however, using JDT tools and XDoclet tags. 1. Right click on ejbs and select New -> Other -> Java -> Class, click Next.

2. Fill in the following information: Package: ejbs, Name: PaymentVoucherItemBean, Modifiers: public and abstract, Superclass: java.lang.Object, Interfaces: javax.ejb.EntityBean. Then click finish.

3. Now, open ejbs.PaymentVoucherItemBean.java in the Java editor. XDoclet tags need to be added in order for XDoclet to properly generate all the necessary code and ejb meta data. Start by adding the following javadoc to the bean class itself (right above the line: public abstract class PaymentVoucherItemBean). This code specifies that this bean is a CMP, should only have local interface, defines the interfaces names, and specifies that the primary key is type java.lang.Integer and is handled by field 'id'. /** * 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. private static int PRIMKEY = (int) System.currentTimeMillis(); /** * 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). * @ejb.finder signature="java.util.Collection findAll()" * query="select object(o) from PaymentVoucher o" * * @ejb.finder signature="java.util.Collection findByIc(String ic)" * query="select object(o) from PaymentVoucher o where o.ic = (?1)" * * @ejb.finder signature="java.util.Collection findByName(String name)" * query="select object(o) from PaymentVoucher o where o.name = (?1)"

* * @ejb.finder signature="java.util.Collection findByPrimaryKey(Integer id)" * query="select object(o) from PaymentVoucher o where o.id = ?1"

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. Adding purpose to PaymentVoucherSessionBean 1. If PaymentVoucherSessionBean is not open, open it in the JavaEditor. The first thing we need to do is add a local reference from the PaymentVoucherSessionBean to the PaymentVoucherItemLocal. This requires the following XDoclet tag at the class level (put this right below the *@ejb.bean name=”PaymentVoucherSession” block). The second tag which starts with @jboss.ejb-local-ref is a JBoss specific XDoclet tag used to setup the JNDI name; other vendors also have their own specific tags where needed. * @ejb.ejb-ref ejb-name="PaymentVoucherItem" view-type="local" * * @jboss.ejb-local-ref ref-name="PaymentVoucherItemLocal" * jndi-name="ejb/ejbs/PaymentVoucherItemLocalHome"

2. Since PaymentVoucherSessionBean will be used by the forthcoming web client instead of PaymentVoucherItemBean, it is necessary to add a few methods to access PaymentVoucherItems. The below code supplies a way for clients to create new PaymentVoucherItems, and find existing ones using the finders we specified previously. Note that PaymentVoucherItems beans are not returned directly, but, rather their data is wrapped up in a PaymentVoucherItemWrapper. The PaymentVoucherItemWrapper will be created in the next step. Delete the existing 'foo' method and add the following methods to PaymentVoucherSessionBean. You will have several compile errors which can be fixed using organized imports (Control-Shift-o); just be sure you select the correct types if there are multiple choices (javax.naming.Context, javax.rmi.PortableRemoteObject, java.util.List, java.util.Iterator). /** * @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(); } } private List wrapPaymentVoucherItemsInList(Collection items) { Iterator iterator = items.iterator(); List list = new ArrayList(items.size()); while (iterator.hasNext()) { PaymentVoucherItemLocal paymentVoucherItem = (PaymentVoucherItemLocal) iterator .next(); PaymentVoucherItemWrapper wrapper = new PaymentVoucherItemWrapper( paymentVoucherItem.getId(), paymentVoucherItem.getType(), paymentVoucherItem.getCode(), paymentVoucherItem .getDescription(), paymentVoucherItem.getAmount(), paymentVoucherItem.getName(), paymentVoucherItem.getIc(), paymentVoucherItem.getPaymentType()); list.add(wrapper); } return list; } private PaymentVoucherItemLocalHome getPaymentVoucherItemLocalHome() { try { Context context = new InitialContext(); Object obj = context .lookup("java:comp/env/ejb/PaymentVoucherItemLocal"); PaymentVoucherItemLocalHome home = (PaymentVoucherItemLocalHome) PortableRemoteObject .narrow(obj, PaymentVoucherItemLocalHome.class); return home; } catch (NamingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }

3. Next, PaymentVoucherItemWrapper needs to be created. Create a new Class called PaymentVoucherItemWrapper in the ejbs package. Be sure to add the java.io.Serializable interface. Then click Finish.

4. Next, open PaymentVoucherItemWrapper in the Java editor and add the following fields. public Integer id; public String type; public String code; public String description; public float amount; public String name; public String ic;

public String paymentType;

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. public PaymentVoucherItemWrapper(Integer id, String type, String code, String description, float amount, String name, String ic, String paymentType) { this.id = id; this.type = type; this.code = code; this.description = description; this.amount = amount; this.name = name; this.ic = ic; this.paymentType = paymentType; } public PaymentVoucherItemWrapper(String type, String code, String description, float amount, String name, String ic, String paymentType) { this.type = type; this.code = code; this.description = description; this.amount = amount;

}

this.name = name; this.ic = ic; this.paymentType = paymentType;

Building a Struts Project The first step is to create a Struts project. The easiest way is to import the struts-blank.war file. 1. Select File -> Import... -> WAR file and click Next.

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.


path="/edit" type="submit.EditAction" name="SubmitForm" input="/edit.jsp" scope="request" validate="true" rel="nofollow">


Creating ActionForm Classes Next, you will create a class which captures input form data that is entered by an end user. An ActionForm class is a JavaBean and each input form data field is mapped to a property of the ActionForm class. Consequently you write getter and setter methods for each of the properties. 1. Select File -> New -> Other -> Java -> Class and then click Next.

2. Fill in 'submit' for the package, and 'SubmitForm' for the class name and then click Finish.

3. Next, open SubmitForm in the Java editor and add the following code. package submit; import org.apache.struts.validator.ValidatorForm; public final class SubmitForm extends ValidatorForm { private String operation; public String getOperation() { return operation; } public void setOperation(String operation) {

}

this.operation = operation;

private String type; public String getType() { return type; } public void setType(String type) { this.type = type; } private String code; public String getCode() { return code; } public void setCode(String code) { this.code = code; } private String description; public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } private String amount; public String getAmount() { return amount; } public void setAmount(String amount) { this.amount = amount; } private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } private String ic; public String getIc() { return ic; } public void setIc(String ic) { this.ic = ic; }

private String paymentType; public String getPaymentType() { return paymentType; } public void setPaymentType(String paymentType) { this.paymentType = paymentType; } private String searchName; public String getSearchName() { return searchName; } public void setSearchName(String searchName) { this.searchName = searchName; } private String searchIC; public String getSearchIC() { return searchIC; } public void setSearchIC(String searchIC) { this.searchIC = searchIC; } }

Creating Action Classes Now you need to create two Action classes which the execute() method of the Action class get invoked by the Struts framework for each request. 1. Select File -> New -> Other -> Java -> Class and then click Next.

2. Fill in 'submit' for the package, and 'ListAction' for the class name and then click Finish.

3. Open ListAction in the Java editor and add the following code to provide business logic of your application. package submit; import import import import import import import

javax.ejb.CreateException; javax.naming.Context; javax.naming.InitialContext; javax.naming.NamingException; javax.rmi.PortableRemoteObject; javax.servlet.http.HttpServletRequest; 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" * */ public final class ListAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { try { PaymentVoucherSessionLocal paymentVoucherSession = getPaymentVoucherSession(); String operation = request.getParameter("operation"); if (operation.equals("add")) { // Cast ActionForm object to SubmitForm type SubmitForm f = (SubmitForm) form; String type = f.getType(); String code = f.getCode(); String description = f.getDescription(); float amount = Float.parseFloat(f.getAmount()); String name = f.getName(); String ic = f.getIc(); String paymentType = f.getPaymentType(); paymentVoucherSession.addPaymentVoucherItem(type, code,

description, amount, name, ic,

paymentType);

request.getSession().setAttribute("items",

paymentVoucherSession.getAllPaymentVoucherItems()); request.getSession().setAttribute("title", "

:: PAYMENT VOUCHER ADDED SUCCESSFULLY ::

"); }

return (mapping.findForward("afterAdd"));

else if (operation.equals("name")) { String name = request.getParameter("searchName"); request.getSession().setAttribute("title", "

:: NAME MATCHING " + name +

"::

");

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", "

:: IC MATCHING " + ic + "::

");

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", "

:: ALL PAYMENT VOUCHERS ::

"); }

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", "

:: PAYMENT VOUCHER UPDATED SUCCESSFULLY ::

"); }

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;

private PaymentVoucherSessionLocalHome paymentVoucherSessionLocalHome; private PaymentVoucherSessionLocal getPaymentVoucherSession() { 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; }

}

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 import import import import import import

javax.ejb.CreateException; javax.naming.Context; javax.naming.InitialContext; javax.naming.NamingException; javax.rmi.PortableRemoteObject; javax.servlet.http.HttpServletRequest; 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" * */ public final class EditAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { 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", "

:: PAYMENT VOUCHER UPDATED SUCCESSFULLY ::

"); }

return (mapping.findForward("afterUpdate"));

else if (operation.equals("index")) { return (mapping.findForward("index")); } }

catch (Exception e) { e.printStackTrace(); } }

return null;

private PaymentVoucherSessionLocalHome paymentVoucherSessionLocalHome; private PaymentVoucherSessionLocal getPaymentVoucherSession() { 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. <%@ <%@ <%@ <%@

page language="java" %> taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %> taglib uri="/WEB-INF/struts-html.tld" prefix="html" %> taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>

Payment Voucher

Payment Vouchers
Type:
Code:
Description:
Amount:
Name:
IC:
Payment Type: Cash Cheque

Name:

IC:



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. <%@ <%@ <%@ <%@

page language="java" %> taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %> taglib uri="/WEB-INF/struts-html.tld" prefix="html" %> taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>

Payment Voucher

"/>
Payment Vouchers
Type:
Code:
Description:
Amount:
Name:
IC:
Payment Type: Cash Cheque


6. Create a JSP page again and fill in 'print.jsp' for the JSP name. And then add the following code. <%@ <%@ <%@ <%@ <%@

page language="java" %> page import="java.util.List, ejbs.PaymentVoucherItemWrapper" %> taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %> taglib uri="/WEB-INF/struts-html.tld" prefix="html" %> taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>

Payment Voucher <%= 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); %> <% } %>
Type Code Description Amount Name IC
Payment Type
&type=<%=item.getType()%> &code=<%=item.getCode()%> &description=<%=item.getDescription()%> &amount=<%=item.getAmount()%> &name=<%=item.getName()%> &ic=<%=item.getIc()%> &paymentType=<%=item.getPaymentType()%>">Edit ">Delete <%= item.getType() %> <%= item.getCode() %> <%= item.getDescription() %> <%= item.getAmount() %> <%= item.getName() %> <%= item.getIc() %> <%= item.getPaymentType() %>



Creating web.xml file In this application, you need to define the ActionServlet into web.xml configuration file, which functions as a controller from the standpoint of the Model-View-Controller framework. Every web application must have a web.xml configuration file since Struts application is a web application. Before you adding the configuration, you need to run XDoclet to generate jboss-web.xml. It is because XDoclet will clear the content for ActionServlet definition and generate its own web.xml. 1. Right click on StrutsPaymentVoucher and then select Run XDoclet. After that, XDoclet will generate a file call jboss-web.xml as you can see at WEB-INF directory.

2. Next, open web.xml in the Text editor and add the following XML tags into web-app tag. <servlet> <servlet-name>action <servlet-class>org.apache.struts.action.ActionServlet <param-name>config <param-value>/WEB-INF/struts-config.xml <param-name>debug <param-value>2 <param-name>detail

<param-value>2
2 <servlet-mapping> <servlet-name>action *.do <welcome-file-list> <welcome-file>index.jsp /tags/struts-bean /WEB-INF/struts-bean.tld /tags/struts-html /WEB-INF/struts-html.tld /tags/struts-logic /WEB-INF/struts-logic.tld /tags/struts-nested /WEB-INF/struts-nested.tld /tags/struts-tiles /WEB-INF/struts-tiles.tld <ejb-local-ref> <ejb-ref-name>ejb/PaymentVoucherSession <ejb-ref-type>Session ejbs.PaymentVoucherSessionLocalHome ejbs.PaymentVoucherSessionLocal <ejb-link>PaymentVoucherSession

Running And Testing The Payment Voucher Web Application Your payment voucher application is now complete. Now it is time to take it for a spin. 1. Select Window -> Show View -> Other... -> Server -> Servers and click OK.

2. Right click on the servers view and select New -> Server.

3. Select 'JBoss v3.2.3' under JBoss and click Finish.

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.