At line 1 changed 1 line. |
__Part V:__ [Adding Validation and List Screen|ValidationAndListSpring] - Adding validation logic to the person object so that firstName and lastName are required fields and adding a list screen to display all person records in the database. |
__Part IV:__ [Adding Validation and List Screen|ValidationAndListSpring] - Adding validation logic to the Person object so that firstName and lastName are required fields and adding a list screen to display all person records in the database. |
At line 3 changed 1 line. |
;:''This tutorial depends on __Part IV:__ [Configuring Tiles and FormController|ConfiguringTilesSpring].'' |
;:''This tutorial depends on __Part III:__ [Creating Controllers and JSPs|SpringControllers].'' |
At line 6 changed 1 line. |
This tutorial will show you how to add Validation logic (client and server-side) to the personForm object using Struts' Validator. We'll also create a list screen using the [Display Tag Library|http://displaytag.sf.net] to display all the people in the database. |
This tutorial will show you how to add Validation logic (client and server-side) to the Person object using Commons Validator. We'll also create a list screen using the [Display Tag Library|http://displaytag.sf.net] to display all the people in the database. |
At line 11 changed 1 line. |
* [1] Add XDoclet Validator to Person.java |
* [1] Add XDoclet Validator tags to Person.java |
At line 14 changed 2 lines. |
* [5] Add ''testSearch'' methods to Action Test |
* [6] Add ''search '' method to Action |
* [4] Add ''getPeople'' methods to PersonDao and Manager |
* [5] Create PersonControllerTest |
* [6] Create PersonController |
At line 20 changed 1 line. |
To use Commons Validator with Spring MVC, normally you have to write a validation.xml file by hand. However, using XDoclet, it's much easier - we just need to add a couple of ''@spring.validator'' tags to our POJO (Person.java). Let's open it up (src/dao/**/persistence/Person.java) and modify your setFirstName and setLastName methods to resemble the following: |
To use Commons Validator with Spring MVC, normally you have to write a validation.xml file by hand. However, thanks to XDoclet, it's much easier - you just need to add a couple of ''@spring.validator'' tags to our POJO (Person.java). Let's open it up (src/dao/**/dao/Person.java) and modify your setFirstName and setLastName methods to resemble the following: |
At line 43 changed 1 line. |
@struts.validator type="required" msgkey="errors.required" |
@spring.validator type="required" msgkey="errors.required" |
At line 66 changed 1 line. |
To enable validation in our personForm.jsp, you'll need to make sure your personForm.jsp has the following at the bottom: |
To enable validation in personForm.jsp, you'll need to make sure your personForm.jsp has the following at the bottom: |
At line 68 changed 1 line. |
{{{<html:javascript formName="person" cdata="false" |
{{{<v:javascript formName="person" cdata="false" |
At line 89 changed 1 line. |
Now that we have Validation configured for this form, let's make sure it works. Run __ant db-load deploy__, start Tomcat and go to [http://localhost:8080/appfuse/editPerson.html?id=1]. |
Now that we have Validation configured for this form, let's make sure it works. Run __ant db-load deploy__, start Tomcat and go to [http://localhost:8080/appfuse/editPerson.html?id=1]. One thing you might notice is that the "First Name" and "Last Name" labels now have asterisks next to them - indicating required fields. This is achieved with a LabelTag that looks up the validation rules from Commons Validator. |
At line 99 changed 2 lines. |
%%(border: 1px solid black; margin: 0 auto; height: 202px; width: 423px) |
[validation-required-nojs.png] |
%%(border: 1px solid black; margin: 0 auto; height: 215px; width: 521px) |
[ValidationAndList/validation-required-nojs.png] |
At line 103 removed 1 line. |
If you don't see these validation errors, there are a couple possibilities: |
At line 105 removed 5 lines. |
* The form saves with a success message, but the firstName and lastName fields are now blank. |
;:''This is because the <html:form> in web/pages/personForm.jsp has action="editPerson" - make sure it has __action="savePerson"__.'' |
* You click save, but a blank page appears. |
;:''The blank page indicates that the "input" attribute of you "savePerson" forward is incorrectly configured. Make sure it relates to a local or global action-forward. In this example, it should be __input="edit"__, which points to the .personDetail tile's definition. From my experience, the input's value must be a forward, not a path to an action.'' |
|
At line 114 changed 1 line. |
<html:javascript formName="personForm" cdata="false" |
<v:javascript formName="personForm" cdata="false" |
At line 123 changed 1 line. |
Open test/dao/**/persistence/PersonDaoTest.java and add a ''testGetPeople'' method: |
Open test/dao/**/dao/PersonDaoTest.java and add a ''testGetPeople'' method: |
At line 128 changed 1 line. |
person = new Person(); |
person = new Person(); |
At line 134 changed 1 line. |
The reason I'm passing in a person object to the ''getPeople'' method is to allow for filtering (based on values in person) in the future. |
The reason I'm passing in a person object to the ''getPeople'' method is to allow for filtering (based on values in person) in the future. Adding this parameter in your getPeople() method signature is optional, but the rest of this tutorial assumes you have done this. |
At line 140 changed 3 lines. |
public void testGetPeople() { |
List results = mgr.getPeople(new Person()); |
assertTrue(results.size() > 0); |
public void testGetPeople() throws Exception { |
List results = new ArrayList(); |
person = new Person(); |
results.add(person); |
|
// set expected behavior on dao |
personDao.expects(once()).method("getPeople") |
.will(returnValue(results)); |
|
List people = personManager.getPeople(null); |
assertTrue(people.size() == 1); |
personDao.verify(); |
At line 146 changed 1 line. |
Save all your files and make sure everything compiles with __ant clean compile__. Now you should be able to run both tests by running the following: |
In order for these tests to compile, you need to add the ''getPeople()'' method to the PersonDao and PersonManager interfaces, and their implementations. |
At line 148 changed 2 lines. |
* __ant test-dao -Dtestcase=PersonDao__ |
* __ant test-service -Dtestcase=PersonManager__ |
!!Add getPeople() method to DAO and Manager [#4] |
Open src/dao/**/dao/PersonDao.java and add the getPeople() method signature: |
At line 151 changed 1 line. |
If everything works - ''nice job!'' Now we need to add this ''retrieve all'' functionality to the web tier. |
[{Java2HtmlPlugin |
At line 153 changed 2 lines. |
!!Add testSearch method to Action Test [#5] |
Open test/web/**/action/PersonActionTest.java and add the following method: |
public List getPeople(Person person); |
}] |
At line 156 changed 1 line. |
;:%%(color: blue)''I copied the testSearch method from UserActionTest.java and changed the "User" stuff to "Person".'' |
Now add the same method signature to src/service/**/service/__PersonManager.java__. Save all your files and adjust the imports in your tests. Next you need to implement the getPeople() method in your implementation classes. Open src/dao/**/dao/hibernate/PersonDaoHibernate.java and add the following method: |
At line 160 changed 9 lines. |
public void testSearch() { |
setRequestPathInfo("/editPerson"); |
addRequestParameter("action", "Search"); |
actionPerform(); |
|
verifyForward("list"); |
|
assertTrue(getRequest().getAttribute(Constants.PERSON_LIST) != null); |
verifyNoActionErrors(); |
public List getPeople(Person person) { |
return getHibernateTemplate().find("from Person"); |
At line 172 changed 1 line. |
This class will not compile until you add the PERSON_LIST variable to the src/dao/**/Constants.java file. |
<div class="note" style="margin-left: 30px"> |
You'll notice here that nothing is being done with the ''person'' parameter. This is just a placeholder for now - in the future you may want to filter on it's properties using [Hibernate's Query Language|http://www.hibernate.org/hib_docs/reference/en/html/queryhql.html] (HQL) or using [Criteria Queries|http://www.hibernate.org/hib_docs/reference/en/html/querycriteria.html]. |
At line 174 changed 1 line. |
;:%%(color: blue)''I usually copy a similar variable that already exists in this file - i.e. USER_LIST.'' |
''An example using a Criteria Query:'' |
At line 178 changed 4 lines. |
/** |
* The request scope attribute that holds the person list |
*/ |
public static final String PERSON_LIST = "personList"; |
Example example = Example.create(person) |
.excludeZeroes() // exclude zero valued properties |
.ignoreCase(); // perform case insensitive string comparisons |
try { |
return getSession().createCriteria(Person.class) |
.add(example) |
.list(); |
} catch (Exception e) { |
throw new DataAccessException(e.getMessage()); |
} |
return new ArrayList(); |
|
At line 189 added 1 line. |
</div> |
At line 184 changed 1 line. |
Now save all your changes. You won't be able to run __ant test-cactus -Dtestcase=PersonAction__ yet since ''PersonAction.search()'' does not exist (yet). Let's add it. |
Now implement the ''getPeople()'' method in src/service/**/impl/PersonManagerImpl.java: |
At line 186 removed 3 lines. |
!!Add search method to Action [#6] |
Open src/web/**/action/PersonAction.java and add the following XDoclet tag at the top - to forward to our list screen. |
|
At line 191 changed 1 line. |
* @struts.action-forward name="list" path=".personList" |
public List getPeople(Person person) { |
return dao.getPeople(person); |
} |
At line 194 changed 1 line. |
Now add the search method to the body of the PersonAction class. |
After saving all your changes, you should be able to run both tests by executing the following: |
At line 196 changed 1 line. |
;:%%(color: blue)''I used UserAction.search() as a template for this method.'' |
* __ant test-dao -Dtestcase=PersonDao__ |
* __ant test-service -Dtestcase=PersonManager__ |
At line 205 added 9 lines. |
If everything works - ''nice job!'' Now you need to add this ''retrieve all'' functionality to the web tier. |
|
!!Create PersonControllerTest [#5] |
In the last couple of tutorials, we've been working with the PersonFormController to interact with our HTML form. Now we need to create a new Controller that'll simply handle getting and displaying a list of people in the database. |
|
;:''You could also use a [MultiActionController|http://www.springframework.org/docs/api/org/springframework/web/servlet/mvc/multiaction/MultiActionController.html] to handle all your List screens.'' |
|
To begin, create test/web/**/action/PersonControllerTest.java (extends BaseControllerTestCase) and add the following method: |
|
At line 200 changed 7 lines. |
public ActionForward search(ActionMapping mapping, ActionForm form, |
HttpServletRequest request, |
HttpServletResponse response) |
throws Exception { |
if (log.isDebugEnabled()) { |
log.debug("Entering 'search' method"); |
} |
package org.appfuse.webapp.action; |
At line 208 changed 4 lines. |
// Exceptions are caught by ActionExceptionHandler |
PersonManager mgr = (PersonManager) getBean("personManager"); |
List people = mgr.getPeople(null); |
request.setAttribute(Constants.PERSON_LIST, people); |
import java.util.Map; |
At line 213 changed 2 lines. |
// return a forward to the person list definition |
return mapping.findForward("list"); |
import javax.servlet.http.HttpServletRequest; |
import javax.servlet.http.HttpServletResponse; |
|
import org.appfuse.Constants; |
import org.springframework.web.servlet.ModelAndView; |
|
public class PersonControllerTest extends BaseControllerTestCase { |
|
public void testHandleRequest() throws Exception { |
PersonController c = (PersonController) ctx.getBean("personController"); |
ModelAndView mav = c.handleRequest((HttpServletRequest) null, |
(HttpServletResponse) null); |
Map m = mav.getModel(); |
assertNotNull(m.get(Constants.PERSON_LIST)); |
assertEquals(mav.getViewName(), "personList"); |
At line 236 added 1 line. |
} |
At line 218 changed 1 line. |
Now if you run __ant test-cactus -Dtestcase=PersonAction__, you will get an error that the .personList definition does not exist. Or, at least that is what the following error is trying to say: |
This class will not compile until you (1) create the PersonController class and (2) add the PERSON_LIST variable to the src/dao/**/Constants.java file. Some folks have suggested that this class be named ''PersonControllerList'' - the name choice is up to you. I prefer Controller and FormController because it tells me one implements [Controller|http://www.springframework.org/docs/api/org/springframework/web/servlet/mvc/Controller.html] while the latter extends [SimpleFormController|http://www.springframework.org/docs/api/org/springframework/web/servlet/mvc/SimpleFormController.html]. |
At line 220 changed 4 lines. |
{{{ |
Testcase: testSearch(org.appfuse.webapp.action.PersonActionTest): FAILED |
was expecting '/appfuse/.personList' but received '/appfuse.personList' |
}}} |
;:%%(color: blue)''I usually copy a similar variable that already exists in this file - i.e. USER_LIST.'' |
At line 225 changed 2 lines. |
!!Create personList.jsp and Canoo test [#7] |
Let's create the JSP to hold our list and a Tile's definition for it. There should already be a personList.jsp in the ''web'' folder of your project. Copy this file to web/pages/personList.jsp. If it's not there, you can use the ViewGen Tool to create it. To do this from the command-line, navigate to extras/viewgen and run __ant -Dform.name=PersonForm__. This will generate a PersonFormList.jsp in extras/viewgen/build. |
[{Java2HtmlPlugin |
At line 228 changed 1 line. |
Once personList.jsp exists in ''web/pages'', open it for editing. |
/** |
* The request scope attribute that holds the person list |
*/ |
public static final String PERSON_LIST = "personList"; |
}] |
At line 230 changed 1 line. |
At the top of the file is a <bean:struts> tags that exposes the edit screen's forward as a page-scoped variable. This should already have a value of "editPerson". |
Now save all your changes. You won't be able to run __ant test-web -Dtestcase=PersonController__ yet since ''PersonController'' does not exist (yet). Let's add it. |
At line 253 added 3 lines. |
!!Create PersonController [#6] |
Create src/web/**/action/PersonController.java. It should implement {{org.springframework.web.servlet.mvc.Controller}} and read as follows: |
|
At line 234 changed 3 lines. |
<%-- For linking to edit screen --%> |
<bean:struts id="editURL" forward="editPerson"/> |
}] |
package org.appfuse.webapp.action; |
At line 238 changed 1 line. |
Now we need to add this to the metadata/web/global-forwards.xml, as well as one for viewing the list. This way, they will get included in our struts-config.xml file. |
import javax.servlet.http.HttpServletRequest; |
import javax.servlet.http.HttpServletResponse; |
At line 240 changed 1 line. |
[{Java2HtmlPlugin |
import org.apache.commons.logging.Log; |
import org.apache.commons.logging.LogFactory; |
At line 242 changed 2 lines. |
<forward name="editPerson" path="/editPerson.html"/> |
<forward name="viewPeople" path="/editPerson.html?action=Search"/> |
import org.appfuse.Constants; |
import org.appfuse.model.Person; |
import org.appfuse.service.PersonManager; |
|
import org.springframework.web.servlet.ModelAndView; |
import org.springframework.web.servlet.mvc.Controller; |
|
public class PersonController implements Controller { |
private final Log log = LogFactory.getLog(PersonController.class); |
private PersonManager mgr = null; |
|
public void setPersonManager(PersonManager personManager) { |
this.mgr = personManager; |
} |
|
public ModelAndView handleRequest(HttpServletRequest request, |
HttpServletResponse response) |
throws Exception { |
if (log.isDebugEnabled()) { |
log.debug("entering 'handleRequest' method..."); |
} |
|
return new ModelAndView("personList", Constants.PERSON_LIST, |
mgr.getPeople(new Person())); |
} |
} |
|
At line 246 changed 1 line. |
In the first <button> you find in personList.jsp, we need to populate another forward - this time to the Add screen. Make sure your button's onclick event matches the following: |
Now add a definition to web/WEB-INF/action-servlet.xml for this Controller. |
At line 250 changed 1 line. |
onclick="location.href='<html:rewrite forward="editPerson"/>'"> |
<bean id="personController" class="org.appfuse.webapp.action.PersonController"> |
<property name="personManager"><ref bean="personManager"/></property> |
</bean> |
At line 253 changed 1 line. |
The template we used to create this JSP has the column for the id property hard-coded, so XDoclet adds it twice. We need to remove this from personList.jsp - so delete the following from this file: |
Now if you run __ant test-web -Dtestcase=PersonController__, the test should pass. Next, create a URL mapping for this controller. To do this, search for the "urlMapping" bean in web/WEB-INF/action-servlet.xml and add the following line to the "mappings" property: |
At line 257 changed 2 lines. |
<display:column property="id" sort="true" headerClass="sortable" |
titleKey="personForm.id"/> |
<prop key="/people.html">personController</prop> |
At line 261 changed 1 line. |
;:''If anyone knows of a way to modify the extras/viewgen/src/List_jsp.xdt to not include this column tag, please let me know.'' |
!!Create personList.jsp and Canoo test [#7] |
Open the personList.jsp file in the ''web/pages'' folder of your project. One thing you'll probably want to change is the plural form of the items you're listing. The generated name in this example is "persons" and it should probably be people. At or near line 31, you should have the following line: |
At line 263 removed 2 lines. |
Another thing you'll probably want to change is the plural form of the items you're listing. The generated name in this example is "persons" and it should probably be people. At or near line 31, you should have the following line: |
|
At line 271 changed 1 line. |
Now we need to add a new definition to tiles-config.xml for this list screen. Open web/WEB-INF/tiles-config.xml and add the following XML: |
Finally, add the title and heading keys (personList.title and personList.heading) to web/WEB-INF/classes/ApplicationResources.properties. Open this file and add the following: |
At line 273 removed 14 lines. |
;:%%(color: blue)''I usually copy an existing list definition - i.e. .userList.'' |
|
[{Java2HtmlPlugin |
|
<!-- Person List definition --> |
<definition name=".personList" extends=".mainMenu"> |
<put name="titleKey" value="personList.title" /> |
<put name="headingKey" value="personList.heading" /> |
<put name="content" value="/WEB-INF/pages/personList.jsp"/> |
</definition> |
}] |
|
Finally, we need to add these keys (personList.title and personList.heading) to web/WEB-INF/classes/ApplicationResources_en.properties. Open this file and add the following: |
|
At line 293 changed 2 lines. |
As a reminder, the {{personList.title}} is what ends up in the brower's title bar (the <title> tag) and |
{{personList.heading}} will be put into an <h1> tag before any page content. At this point, your PersonActionTest should succeed. Save all your changes, navigate to the basedir of your project and try it by executing __ant test-cactus -Dtestcase=PersonAction__. |
As a reminder, the {{personList.title}} is what ends up in the browser's title bar (the <title> tag) and |
{{personList.heading}} will be put into an <h1> tag before any page content. At this point, you could be able to run "ant deploy", start Tomcat and [open the list screen in your browser|http://localhost:8080/appfuse/people.html]. |
At line 296 changed 5 lines. |
%%(color:green) |
''__Sweet!__''\\ |
BUILD SUCCESSFUL\\ |
Total time: 1 minute 0 seconds |
%% |
Now that we have a List Screen, let's change the pages that are displayed after adding and deleting a new Person. In web/WEB-INF/action-servlet.xml, change the personFormController's successView property to be "people.html". |
At line 302 removed 4 lines. |
At this point, you should be able to view this page in your browser at [http://localhost:8080/appfuse/editPerson.do?action=Search]. |
|
Now that we have a List Screen, let's change the pages that are displayed after adding and deleting a new Person. In src/web/**/PersonAction.java, change the ''mapping.findForward("mainMenu")'' in the ''save'', ''delete'' and ''cancel'' methods to be: |
|
At line 308 changed 1 line. |
return mapping.findForward("viewPeople"); |
<property name="successView"><value>people.html</value></property> |
At line 311 changed 1 line. |
You will also need to change ''verifyForward("list")'' to be ''verifyForward("viewPeople")'' in the testRemove method of test/web/**/PersonActionTest.java. Lastly, the Canoo tests "AddPerson" and "DeletePerson" need to be updated. Open test/web/web-tests.xml and change the following line in the "AddPerson" target: |
You will also need to update the Canoo tests "AddPerson" and "DeletePerson". Open test/web/web-tests.xml and change the following line in the "AddPerson" target: |
At line 323 changed 2 lines. |
{{{<verifytitle description="display Main Menu" |
text=".*$(mainMenu.title}.*" regex="true"/> |
{{{<verifytitle description="display Main Menu" text=".*$(mainMenu.title}.*" regex="true"/> |
At line 329 changed 2 lines. |
{{{<verifytitle description="display Person List" |
text=".*$(personList.title}.*" regex="true"/>}}} |
{{{<verifytitle description="display Person List" text=".*${personList.title}.*" regex="true"/>}}} |
At line 332 changed 1 line. |
We use "viewPeople" instead of "list" so that the search method will be executed, rather than simply forwarding to the .personList definition (which the "list" forward points to). |
To test that displaying this page works, you can create a new JSP test in test/web/web-tests.xml: |
At line 334 removed 2 lines. |
To test that displaying this page works, we can create a new JSP test in test/web/web-tests.xml: |
|
At line 345 changed 1 line. |
<invoke description="click View People link" url="/editPerson.html?action=Search"/> |
<invoke description="click View People link" url="/people.html"/> |
At line 381 added 1 line. |
|
At line 366 changed 1 line. |
Now you can run __ant test-canoo -Dtestcase=SearchPeople__ (or ''ant test-jsp'' if Tomcat isn't running) and hopefully it will result in "BUILD SUCCESSFUL". If so - ''nice work!'' |
Now you can run __ant deploy test-canoo -Dtestcase=SearchPeople__ (or ''ant test-jsp'' if Tomcat isn't running) and hopefully it will result in "BUILD SUCCESSFUL". If so - ''nice work!'' |
At line 374 changed 3 lines. |
<html:link forward="viewPeople"> |
<fmt:message key="menu.viewPeople"/> |
</html:link> |
<a href="<c:url value="/people.html"/>"><fmt:message key="menu.viewPeople"/></a> |
At line 380 changed 1 line. |
Where ''menu.viewPeople'' is an entry in web/WEB-INF/classes/ApplicationResources_en.properties. |
Where ''menu.viewPeople'' is an entry in web/WEB-INF/classes/ApplicationResources.properties. |
At line 389 changed 1 line. |
<Menu name="PeopleMenu" title="menu.viewPeople" forward="viewPeople"/> |
<Menu name="PeopleMenu" title="menu.viewPeople" page="/people.html"/> |
At line 410 changed 1 line. |
Now if you run __ant clean deploy__ and start Tomcat, you should see something like the screenshot below. |
Now if you run __ant clean deploy__, start Tomcat and go to [http://localhost:8080/appfuse/mainMenu.html], you should see something like the screenshot below. |
At line 413 changed 1 line. |
[new-menu-item.png] |
[ValidationAndList/new-menu-item.png] |
At line 419 changed 1 line. |
You've completed the full lifecycle of developing a set of master-detail pages with AppFuse - __congratulations__. Now the real test is if you can run all the tests in your app without failure. To test, stop tomcat and run __ant clean test-all__. This will run all the unit tests within your project. As a reminder, it should be easy to setup and test AppFuse from scratch using __ant setup-db setup-tomcat test-all__. Also, if you're looking for more robust examples - checkout [StrutsResume]. |
You've completed the full lifecycle of developing a set of master-detail pages with AppFuse and Spring's MVC framework - __Congratulations__! Now the real test is if you can run all the tests in your app without failure. To test, stop tomcat and run __ant clean test-all__. This will run all the unit tests within your project. As a reminder, it should be easy to setup and test AppFuse from scratch using __ant setup-db setup-tomcat test-all__. Also, if you're looking for more robust examples - checkout [Struts Resume|StrutsResume]. |
At line 424 changed 1 line. |
Total time: 2 minutes 31 seconds |
Total time: 4 minutes 21 seconds |