About this Tutorial
This tutorial will show you how to create master/detail screens with Struts 2. The list (master) screen will have the ability to sort columns, as well as page 25 records at a time. The form (detail) screen will use a responsive CSS form layout (courtesy of Bootstrap). You will also configure client and server-side validation to improve your users' experience.
|IntelliJ IDEA Rocks|
This tutorial assumes you've created a project with the appfuse-basic-struts archetype and have already completed the Persistence and Services tutorials. If you're using the appfuse-modular-struts archetype, please morph your mind into using the web module as the root directory. If you created your project with a different web framework than Struts, you're likely to be confused and nothing will work in this tutorial.
Table of Contents
- Introduction to Struts 2
- Create a PersonActionTest
- Create a PersonAction that will fetch people
- Create personList.jsp to show search results
- Modify PersonActionTest and PersonAction for edit(), save() and delete() methods
- Create personForm.jsp to edit a person
- Configure Validation
- Create a Canoo WebTest to test browser-like actions
- Add link to menu
The code for this tutorial is located in the "tutorial-struts" module of the appfuse-demos project on GitHub. Use the following command to check it out from Subversion:
svn co https://github.com/appfuse/appfuse-demos/trunk/tutorial-struts2
Introduction to Struts 2
Struts 2 (formerly WebWork) is a web framework designed with simplicity in mind. It's built on top of XWork, which is a generic command framework. XWork also has an IoC container, but it isn't as full-featured as Spring and won't be covered in this section. Struts 2 controllers are called Actions, mainly because they must implement the Action interface. The ActionSupport class implements this interface, and it is most common parent class for Struts 2 actions.
The figure below shows how Struts 2 fits into a web application's architecture.
Struts 2 actions typically contain methods for accessing model properties and methods for returning strings. These strings are matched with "result" names in a struts.xml configuration file. Actions typically have a single execute() method, but you can easily add multiple methods and control execution using URLs and button names.
Struts 2 uses interceptors to intercept the request and response process. This is much like Servlet Filters, except you can talk directly to the action. Struts 2 uses interceptors in the framework itself. A number of them initialize the Action, prepare it for population, set parameters on it and handle any conversion errors.
Create a PersonActionTest
Testing is an important part of any application, and testing a Struts application is easier than most. The generic command pattern provided by XWork doesn't depend on the Servlet API at all. This makes it easy to use JUnit to test your Actions.
PersonActionTest.java class in src/test/java/**/webapp/action.
This class won't compile yet; you must first create the
Create a PersonAction that will fetch people
PersonAction.java class (that extends AppFuse's BaseAction) in src/main/java/**/webapp/action:
Struts 2 actions are typically both the controller and the model. In this example, the
list() method acts as the controller, and the
getPersons() method retrieves data from the model. This simplification of the MVC paradigm makes this web framework very easy to program with.
PersonActionTest using your IDE or mvn test -Dtest=PersonActionTest.
Struts' Zero Configuration feature is turned on by default. If you want to configure your Actions as Spring beans, you can do that by using class="beanId" in your Action definition, and then defining the bean in applicationContext.xml. Otherwise, they will automatically be wired up by name with Spring dependencies. All you need to do is add a setter to your Action to get a Spring bean injected into it.
Create personList.jsp to show search results
Create a src/main/webapp/WEB-INF/pages/personList.jsp page to display the list of people:
struts.xml file in the src/main/resources directory. Define an <action> (at the bottom of this file) and set its class attribute to match the fully-qualified class name of the PersonAction class.
The default result type is "dispatcher" and its name is "success". This configured result type simply forwards you to the
personList.jsp file when "success" is returned from
PersonAction.list(). Other result types include redirect and chain. Redirect performs a client-side redirect and chain forwards you to another action. For a full list of result types, see Struts 2's Result Types documentation.
The "method" attribute of this action has a
list attribute, which calls the
list() method when the "persons" URL is invoked. If you exclude the method attribute, it calls the
Open src/main/resources/ApplicationResources.properties and add i18n keys/values for the various "person" properties:
Run mvn jetty:run and open http://localhost:8080/persons in your browser. Login with admin/admin and you should see a screen similar to the figure below.
Security settings for AppFuse specify that most url-patterns should be protected (except for /signup and /passwordHint). This guarantees that clients must go through an Action to get to a JSP (or at least the ones in WEB-INF/pages).
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:
Modify PersonActionTest and PersonAction for edit(), save() and delete() method
To create the detail screen, add
delete() methods to the PersonAction class. Before doing this, create tests for these methods.
Open src/test/java/**/webapp/action/PersonActionTest.java and add test methods for edit, save, and delete operations:
This class will not compile yet because you need to update your src/main/java/**/action/PersonAction.java class. The cancel and delete properties capture the click of the Cancel and Delete buttons. The
execute() method routes the different actions on the form to the appropriate method.
If you look at your
PersonActionTest, all the tests depend on having a record with id=1 in the database (and testRemove depends on id=2), so let's add those records to our sample data file (src/test/resources/sample-data.xml). Adding it at the bottom should work - order is not important since it (currently) does not relate to any other tables. If you already have this table, make sure the 2nd record exists so
testRemove() doesn't fail.
DbUnit loads this file before you run any tests, so this record will be available to your Action test.
Save all your files and run the tests in
PersonActionTest using the command mvn test -Dtest=PersonActionTest.
Total time: 6.440s
Create personForm.jsp to edit a person's information
Create a src/main/webapp/WEB-INF/pages/personForm.jsp page to display the form:
Struts reduces the amount of HTML you have to write for a form. The <s:form> tag writes the <form> and structure tags for you. The <s:textfield> tag writes the whole row, including the <div> and <label> tags to hold the input field's label.
Next, update the src/main/resources/struts.xml file to include the "editPerson" and "savePerson" actions.
Run mvn jetty:run, open your browser to http://localhost:8080/persons, and click on the Add button.
Fill in the first name and last name fields and click the Save button. This should route you to the list screen, where a success message flashes and the new person displays in the list.
|Displaying success messages|
The src/main/webapp/common/messages.jsp file in AppFuse renders the success message in this screen. This file is included in decorators/default.jsp. It also handles displaying validation errors:
Struts 2 allows two types of validation: per-action and model-based. Since you likely want the same rules applied for the person object across different actions, this tutorial will use model-based.
Create a new file named Person-validation.xml in the src/main/resources/**/model directory (you'll need to create this directory). It should contain the following XML:
The "errors.message" key in errors*.properties (listed below) will use the field's "name" attribute to do internationalization. You can also give the <message> element a body if you don't need i18n.
Now you need to configure
PersonAction to know about visitor validation. To do this, create a
PersonAction-validation.xml file in src/main/resources/**/webapp/action (you'll need to create this directory). Fill it with the following XML:
Unfortunately, Struts doesn't have a transparent mechanism for reading from the
Client-side validation of model-based validation rules doesn't work with the Struts setup that AppFuse uses. Furthermore, I believe that Struts's client-side validation needs some additional features, namely: allow cancelling and showing all errors in one dialog. Because of this, only server-side validation works in Struts+AppFuse. If you'd like, you can read more about my frustrations with client-side validation.
As a workaround, you can use per-action validation. Just copy the
Struts' validation interceptor is enabled by default, so you don't need to configure anything for validation to work.
After saving all your files and running mvn jetty:run, validation should kick in when you try to save this form. To test, go to http://localhost:8080/editPerson?id=1. If you erase the values in the firstName and lastName fields and click the Save button, you should see the following:
AppFuse is configured so that methods cancel, execute, delete, edit, list, and start are not validated. This allows you to go back from a form with errors on (like above) by pressing the Cancel button.
Create a Canoo WebTest to test browser-like actions
The next (optional) step in this tutorial is to create a Canoo WebTest to test the JSPs. This step is optional, because you can run the same tests manually through your browser. Regardless, it's a good idea to automate as much of your testing as possible.
You can use the following URLs to test the different actions for adding, editing and saving a user.
- Add - http://localhost:8080/editPerson.
- Edit - http://localhost:8080/editPerson?id=1.
- Delete - Use the edit link above and click on the Delete button.
- Save - Click edit and then click the Save button.
There is a WebTest Recorder Firefox plugin that allows you to record your tests, rather than manually writing them.
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 src/test/resources/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.
After adding this, you should be able to run mvn verify and have these tests execute. If this command results in "BUILD SUCCESS" - nice work!
To include the PersonTests when all Canoo tests are run, add it as a dependency to the "run-all-tests" target in src/test/resources/web-test.xml.
Add link to menu
The last step is to make the list, add, edit and delete functions visible to the user. The simplest way is to add a new link to the list of links in src/main/webapp/WEB-INF/pages/mainMenu.jsp.
menu.viewPeople is an entry in src/main/resources/ApplicationResources.properties.
The other (more likely) alternative is that you'll want to add it to the menu. To do this, add the following to src/main/webapp/WEB-INF/menu-config.xml:
Make sure the above XML is inside the <Menus> tag, but not within another <Menu>. Then open src/main/webapp/common/menu.jsp and add the following code to it:
Now if you run mvn jetty:run and go to http://localhost:8080/mainMenu, you should see something like the screenshot below.
Notice that there is a new link in your main screen (from mainMenu.jsp) and on the top in your menu bar (from menu.jsp).
You've completed the full lifecycle of developing a set of master-detail pages with AppFuse and Struts 2 - Congratulations!
Because it's so much fun to watch tests fly by and success happen, run all your tests again using mvn install.
Happy Day!BUILD SUCCESS
Total time: 52.136s