CreateActions |
|
Your trail: |
This is version 59.
It is not the current version, and thus it cannot be edited.
[Back to current version]
[Restore this version]
Part III: Creating Actions and JSPs - A HowTo for creating Struts Actions and JSPs in the AppFuse architecture.
- This tutorial depends on Part II: Creating new Managers.
About this Tutorial
This tutorial will show you how to create a Struts Action, a JUnit Test (using StrutsTestCase), and a JSP for the form. The Action we create will talk to the PersonManager we created in the Creating Managers tutorial. This tutorial will simplify everything - we will not actually be rendering any data or making the UI look pretty. The next tutorial will show you how to integrate your new JSP into your webapp.
By default, AppFuse ships with Struts as its web framework. As of 1.6, you can use Spring or WebWork as your web framework. Tapestry and JSF are planned for 1.7 and 1.8 respectively.
To install Spring MVC, navigate to extras/spring, and view the README.txt. For WebWork, see extras/webwork/README.txt. You can easily install these options in your project by running "ant install-springmvc" or "ant install-webwork". This tutorial using these two options can be found at:
Let's get started by creating a new Struts Action and JSP your AppFuse project.
- I will tell you how I do stuff in the Real World in text like this.
Table of Contents
- Add XDoclet Tags to Person to generate PersonForm
- Create skeleton JSPs using XDoclet
- Create PersonActionTest to test PersonAction
- Create PersonAction
- Display the JSP in a browser and run the ActionTest
Now let's generate our PersonForm object for Struts and our web tier. To do this, we need to add XDoclet tags to the Person.java Object to create our Struts ActionForm. In the JavaDoc for the Person.java file, add the following @struts.form tags (use User.java if you need an example):
* @struts.form include-all="true" extends="BaseForm"
|
- We extend org.appfuse.webapp.form.BaseForm because it has a toString() method that allows us to call log.debug(formName) to print out a reader-friendly view of the Form object.
- If you haven't renamed the "org.appfuse" packages to "com.company" or otherwise don't have your model class in the default package, you may need to fully-qualify the reference to org.appfuse.webapp.form.BaseForm in the @struts.form tag.
Create skeleton JSPs using XDoclet
In this step, we'll generate a skeleton or our JSP for displaying information from the PersonForm. I say skeleton because it'll just be the <form> itself. It will contain table rows and Struts' <html:text> tags for each property in PersonForm.java. The tool that we use to do this was written by Erik Hatcher. It's basically just a single class (FormTagsHandler.java) and a couple of XDoclet templates (FormKeys.xdt and StrutsForm_jsp.xdt). All these files are located in extras/viewgen.
Here are the simple steps to generating the JSP and a properties file containing the labels for the form elements:
- Execute ant compile - this generates the PersonForm.java from the Person.java POJO.
- From the command-line, navigate to "extras/viewgen"
- Execute ant -Dform.name=PersonForm to generate three files in extras/viewgen/build:
- PersonForm.properties (labels for your form elements)
- personForm.jsp (skeleton JSP file for viewing a single Person)
- PersonFormList.jsp (skeleton JSP file for viewing a list of People)
- Copy the contents of PersonForm.properties into web/WEB-INF/classes/ApplicationResources_en.properties. Here is an example of what you might add to ApplicationResources_en.properties:
# -- person form --
personForm.firstName=First Name
personForm.id=Id
personForm.lastName=Last Name
- Copy personForm.jsp to web/pages/personForm.jsp. Copy PersonFormList.jsp to web/pages/personList.jsp. Notice that each of the new filename's first character is lowercase.
NOTE: If you want to customize the CSS for a particular page, you can add <body id="pageName"/> to the top of the file. This will be slurped up by SiteMesh and put into the final page. You can then customize your CSS on a page-by-page basis using something like the following:
body#pageName element.class { background-color: blue }
- Add keys in ApplicationResources_en.properties the titles and headings in the JSPs
In the generated JSPs, there are two keys for the title (top of the browser window) and the header (heading in the page). We now need to add these two keys (personDetail.title and personDetail.heading) to ApplicationResources_en.properties.
Open web/WEB-INF/classes/ApplicationResources_en.properties and add the following to the bottom of the file:
# -- person detail page --
personDetail.title=Person Detail
personDetail.heading=Person Information
- Just above, we added "personForm.*" keys to this file, so why do I use personForm and personDetail? The best reason is because it gives a nice separation between form labels and text on the page. Another reason is because all the *Form.* give you a nice representation of all the fields in your database. I recently had a client who wanted all fields in the database searchable. This was fairly easy to do. I just looked up all the keys in ApplicationResources.properties which contained "Form." and then put them into a drop-down. On the UI, the user was able to enter a search term and select the column they wanted to search. I was glad I followed this Form vs. Detail distinction on that project!
Create PersonActionTest to test PersonAction
To create a StrutsTestCase Test for PersonAction, start by creating a PersonActionTest.java file in the test/web/**/action directory.
- As usual, copy → save as an existing ActionTest (i.e. UserActionTest). Replace [Uu]ser with [P]erson. You might want to make sure Cactus (StrutsTestCase is an extension of Cactus] tests are running before you copy an existing one. Run ant test-cactus -Dtestcase=UserAction to verify the UserAction works. Stop Tomcat before you do this.
If you did copy UserActionTest, make sure and change UserFormEx to PersonForm. The reason for UserFormEx is to support a String[] setter for Roles. Since the UserForm is generated, it's not very feasible to do it in the User.java object.
package org.appfuse.webapp.action;
public class PersonActionTest extends BaseStrutsTestCase {
public PersonActionTest(String name) {
super(name);
}
public void testEdit() throws Exception {
setRequestPathInfo("/editPerson");
addRequestParameter("action", "Edit");
addRequestParameter("id", "1");
actionPerform();
verifyForward("edit");
assertTrue(request.getAttribute(Constants.PERSON_KEY) != null);
verifyNoActionErrors();
}
public void testSave() throws Exception {
setRequestPathInfo("/editPerson");
addRequestParameter("action", "Edit");
addRequestParameter("id", "1");
actionPerform();
PersonForm personForm =
(PersonForm) request.getAttribute(Constants.PERSON_KEY);
assertTrue(personForm != null);
setRequestPathInfo("/savePerson");
addRequestParameter("action", "Save");
// update the form from the edit and add it back to the request
personForm.setLastName("Feltz");
request.setAttribute(Constants.PERSON_KEY, personForm);
actionPerform();
verifyForward("edit");
verifyNoActionErrors();
}
public void testRemove() throws Exception {
setRequestPathInfo("/editPerson");
addRequestParameter("action", "Delete");
addRequestParameter("id", "2");
actionPerform();
verifyForward("mainMenu");
verifyNoActionErrors();
}
|
You will need to add PERSON_KEY as a variable to the src/dao/**/Constants.java class. The name, "personForm", matches the name given to the form in the struts-config.xml file.
/**
* The request scope attribute that holds the person form.
*/
public static final String PERSON_KEY = "personForm";
|
If you try to run this test, you will get a number of NoSuchMethodErrors - so let's define the edit, save, and delete methods in the PersonAction class.
Create PersonAction
Now we have to create an Action (a.k.a. the Controller) to talk to our Manager and retrieve/save our data. In src/web/**/action, create a PersonAction.java file with the following contents:
package org.appfuse.webapp.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
/**
* @struts.action name="personForm" path="/editPerson" scope="request"
* validate="false" parameter="action" input="mainMenu"
*/
public final class PersonAction extends BaseAction {
public ActionForward cancel(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
return mapping.findForward("mainMenu");
}
public ActionForward delete(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
if (log.isDebugEnabled()) {
log.debug("Entering 'delete' method");
}
ActionMessages messages = new ActionMessages();
PersonForm personForm = (PersonForm) form;
// Exceptions are caught by ActionExceptionHandler
PersonManager mgr = (PersonManager) getBean("personManager");
mgr.removePerson(personForm.getId());
messages.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage("person.deleted",
personForm.getFirstName() + " " +
personForm.getLastName()));
saveMessages(request, messages);
return mapping.findForward("mainMenu");
}
public ActionForward edit(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
if (log.isDebugEnabled()) {
log.debug("Entering 'edit' method");
}
PersonForm personForm = (PersonForm) form;
// if an id is passed in, look up the user - otherwise
// don't do anything - user is doing an add
if (personForm.getId() != null) {
PersonManager mgr = (PersonManager) getBean("personManager");
Person person = mgr.getPerson(personForm.getId());
request.setAttribute(Constants.PERSON_KEY, convert(person));
}
return mapping.findForward("edit");
}
public ActionForward save(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
if (log.isDebugEnabled()) {
log.debug("Entering 'save' method");
}
// Extract attributes and parameters we will need
ActionMessages messages = new ActionMessages();
PersonForm personForm = (PersonForm) form;
boolean isNew = ("".equals(personForm.getId()));
if (log.isDebugEnabled()) {
log.debug("saving person: " + personForm);
}
PersonManager mgr = (PersonManager) getBean("personManager");
mgr.savePerson(convert(personForm));
// add success messages
if (isNew) {
messages.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage("person.added",
personForm.getFirstName() + " " +
personForm.getLastName()));
request.getSession().setAttribute(Globals.MESSAGE_KEY, messages);
return mapping.findForward("mainMenu");
} else {
messages.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage("person.updated",
personForm.getFirstName() + " " +
personForm.getLastName()));
saveMessages(request, messages);
return mapping.findForward("edit");
}
}
}
|
You'll notice in the code above that there are many calls to to convert a PersonForm or a Person object. The convert method is in BaseAction.java (which calls ConvertUtil.convert()) and
uses
BeanUtils.copyProperties
to convert POJOs → ActionForms and ActionForms → POJOs.
- If you are running Eclipse, you might have to "refresh" the project in order to see PersonForm. It lives in build/web/gen, which should be one of your project's source folders. This is the only way for Eclipse to see and import PersonForm, since it is generated by XDoclet and does not live in your regular source tree. If you are not running Eclipse, you will need to manually add "import org.appfuse.webapp.form.PersonForm;" to PersonAction.java and PersonActionTest.java for the generated PersonForm class to be resolved. You will find it in build/web/gen/org/appfuse/webapp/form/PersonForm.java.
- In BaseAction you can register additional Converters (i.e. DateConverter) so that BeanUtils.copyProperties knows how to convert Strings → Objects. If you have Lists on your POJOs (i.e. for parent-child relationships), you will need to manually convert those using the convertLists(java.lang.Object) method.
Now we need to add the edit forward and the savePerson action-mapping, both with are specified in in our PersonActionTest. To do this, we'll add a couple more XDoclet tags to the top of the PersonAction.java file. Do this right above the class declaration. You should already have the XDoclet tag for the editPerson action-mapping, but I'm showing it here so you can see all the XDoclet tags at the top of this class.
/**
* @struts.action name="personForm" path="/editPerson" scope="request"
* validate="false" parameter="action" input="mainMenu"
* @struts.action name="personForm" path="/savePerson" scope="request"
* validate="true" parameter="action" input="edit"
*
* @struts.action-forward name="edit" path=".personDetail"
*/
public final class PersonAction extends BaseAction {
|
The main difference between the editPerson and savePerson action-mappings is that savePerson has validation turned on (see validation="true") in the XDoclet tag above. Note that the "input" attribute must refer to a forward, and cannot be a path (i.e. /editPerson.html). If you'd prefer to use the save path for both edit and save, that's possible too. Just make sure validate="false", and then in your "save" method - you'll need to call form.validate() and handle errors appropriately.
There are a few keys (ActionMessages) that we need to add to ApplicationResources_en.properties to display the success messages. This file is located in web/WEB-INF/classes - open it and add the following:
- I usually add these under the # -- success messages -- comment.
person.added=Information for <strong>{0}</strong> has been added successfully.
person.deleted=Information for <strong>{0}</strong> has been deleted successfully.
person.updated=Information for <strong>{0}</strong> has been updated successfully.
You could use generic added, deleted and updated messages, whatever works for you. It's nice to have separate messages in case these need to change on a per-entity basis.
You might notice that the code we're using to call the PersonManager is the same as the code we used in our PersonManagerTest. Both PersonAction and PersonManagerTest are clients of PersonManagerImpl, so this makes perfect sense.
Everything is almost done for this tutorial, let's get to running our tests!
Run PersonActionTest
If you look at our PersonActionTest, all our tests depend on having a record with id=1 in the database (and testRemove depends on id=2), so let's add that to our sample data file (metadata/sql/sample-data.xml). I'd just add it at the bottom - order is not important since it (currently) does not relate to any other tables.
<table name='person'>
<column>id</column>
<column>first_name</column>
<column>last_name</column>
<row>
<value>1</value>
<value>Matt</value>
<value>Raible</value>
</row>
<row>
<value>2</value>
<value>James</value>
<value>Davidson</value>
</row>
</table>
DBUnit loads this file before we run any of our tests, so this record will be available to our Action test.
Now if you run ant test-cactus -Dtestcase=PersonAction - everything should work as planned. Make sure Tomcat isn't running before you try this.
BUILD SUCCESSFUL
Total time: 1 minute 21 seconds
Clean up the JSP to make it presentable
First, let's clean up our personForm.jsp by making the "id" property a hidden field. Remove the following code block:
<tr>
<th>
<appfuse:label key="personForm.id"/>
</th>
<td>
<html:text property="id" styleId="id"/>
</td>
</tr>
|
And add the following before the <table> tag:
<html:hidden property="id"/>
|
You should probably also change the action of the <html:form> to be "savePerson" so validation will be turned on when saving. Also, change the focus attribute from focus="" to focus="firstName" so the cursor will be in the firstName field when the page loads (this is done with JavaScript).
Now if you execute ant db-load deploy-web, start Tomcat and point your browser to http://localhost:8080/appfuse/editPerson.html?id=1, you should see something like this:
Finally, to make this page more user friendly, you may want to add a message for your users at the top of the form, but this can easily be done by adding text (using <fmt:message>) at the top of the personForm.jsp page.
[Optional] Create a Canoo WebTest to test browser-like actions
The final (optional) step in this tutorial is to create a Canoo WebTest to test the JSPs.
- I say this step is optional, because you can run the same tests through your browser.
You can use the following URLs to test the different actions for adding, editing and saving a user.
Canoo tests are pretty slick in that they're simply configured in an XML file. To add tests for add, edit, save and delete, open test/web/web-tests.xml and add the following XML. You'll notice that this fragment has a target named PersonTests that runs all the related tests.
- I use CamelCase target names (vs. the traditional lowercase, dash-separated) because when you're typing -Dtestcase=Name, I've found that I'm used to doing CamelCase for my JUnit Tests.
<!-- runs person-related tests -->
<target name="PersonTests"
depends="EditPerson,SavePerson,AddPerson,DeletePerson"
description="Call and executes all person test cases (targets)">
<echo>Successfully ran all Person JSP tests!</echo>
</target>
<!-- Verify the edit person screen displays without errors -->
<target name="EditPerson"
description="Tests editing an existing Person's information">
<webtest name="editPerson">
&config;
<steps>
&login;
<invoke description="click Edit Person link" url="/editPerson.html?id=1"/>
<verifytitle description="we should see the personDetail title"
text=".*${personDetail.title}.*" regex="true"/>
</steps>
</webtest>
</target>
<!-- Edit a person and then save -->
<target name="SavePerson"
description="Tests editing and saving a user">
<webtest name="savePerson">
&config;
<steps>
&login;
<invoke description="click Edit Person link" url="/editPerson.html?id=1"/>
<verifytitle description="we should see the personDetail title"
text=".*${personDetail.title}.*" regex="true"/>
<setinputfield description="set lastName" name="lastName" value="Canoo"/>
<clickbutton label="Save" description="Click Save"/>
<verifytitle description="Page re-appears if save successful"
text=".*${personDetail.title}.*" regex="true"/>
</steps>
</webtest>
</target>
<!-- Add a new Person -->
<target name="AddPerson"
description="Adds a new Person">
<webtest name="addPerson">
&config;
<steps>
&login;
<invoke description="click Add Button" url="/editPerson.html"/>
<verifytitle description="we should see the personDetail title"
text=".*${personDetail.title}.*" regex="true"/>
<setinputfield description="set firstName" name="firstName" value="Abbie"/>
<setinputfield description="set lastName" name="lastName" value="Raible"/>
<clickbutton label="${button.save}" description="Click button 'Save'"/>
<verifytitle description="Main Menu appears if save successful"
text=".*${mainMenu.title}.*" regex="true"/>
<verifytext description="verify success message"
text="Information for <strong>Abbie Raible</strong> has been added successfully."/>
</steps>
</webtest>
</target>
<!-- Delete existing person -->
<target name="DeletePerson"
description="Deletes existing Person">
<webtest name="deletePerson">
&config;
<steps>
&login;
<invoke description="click Edit Person link" url="/editPerson.html?id=1"/>
<clickbutton label="${button.delete}" description="Click button 'Delete'"/>
<verifytitle description="display Main Menu" text=".*${mainMenu.title}.*" regex="true"/>
<verifytext description="verify success message"
text="Information for <strong>Matt Canoo</strong> has been deleted successfully."/>
</steps>
</webtest>
</target>
|
After adding this, you should be able to run ant test-canoo -Dtestcase=PersonTests with Tomcat running or ant test-jsp -Dtestcase=PersonTests if you want Ant to start/stop Tomcat for you. To include the PersonTests when all Canoo tests are run, add it as a dependency to the "run-all-tests" target.
You'll notice that there's no logging in the client-side window by Canoo. If you'd like to see what it's doing, you can add the following between </webtest> and </target> at the end of each target.
<loadfile property="web-tests.result"
srcFile="${test.dir}/data/web-tests-result.xml"/>
<echo>${web-tests.result}</echo>
BUILD SUCCESSFUL
Total time: 11 seconds
Next Up: Part V: Adding Validation and List Screen - Adding validation logic to the personForm so that firstName and lastName are required fields and adding a list screen to display all person records in the database.
Attachments:
|