<?xml version="1.0" encoding="UTF-8"?>
<chapter id="practical">
	<title>Practical Use of Spring Web Flow</title>
    <sect1 id="samples">
    	<title>Sample applications</title>
    	<para>
			It is recommended that you review the Spring Web Flow sample applications included in the 
			release distribution for best-practice illustrations of the features of this framework.
			A description of each sample is provided below:
    	</para>
    	<para>
    		<orderedlist>
    			<listitem>
    				<para>
    					<ulink url="http://www.ervacon.com/products/swf/intro/index.html">Phonebook</ulink> - the original sample demonstrating most features (including subflows).
    				</para>
    			</listitem>
    			<listitem>
    				<para>
    					<link linkend="fileupload-sample">Fileupload</link> - demonstrates multipart file upload.
    				</para>
    			</listitem>
    			<listitem>
    				<para>
    					<link linkend="birthdate-sample">Birthdate</link> - demonstrates Struts integration and the MultiAction.
    				</para>
    			</listitem>
    			<listitem>
    				<para>
    					<link linkend="shippingrate-sample">Shippingrate</link> - demonstrates Spring Web Flow together with Ajax technology.
    				</para>
    			</listitem>
    			<listitem>
    				<para>
    					<link linkend="numberguess-sample">NumberGuess</link> - demonstrates use of stateful middle-tier components to carry out business logic.
    				</para>
    			</listitem>
    			<listitem>
                    <para>
                        <link linkend="flowlauncher-sample">Flowlauncher</link> - demonstrates all the possible ways to launch and resume flows.
                    </para>
    			</listitem>
    			<listitem>
                    <para>
                        <link linkend="itemlist-sample">Itemlist</link> - demonstrates REST-style URLs and inline flows.
                    </para>
    			</listitem>
    			<listitem>
    				<para>
                        <link linkend="sellitem-sample">Sellitem</link> - demonstrates a wizard with conditional transitions, flow scope, flow execution redirects, and continuations.
                    </para>
    			</listitem>
    			<listitem>
                    <para>
                        <link linkend="sellitem-JSF-sample">Sellitem-JSF</link> - the 
                            sellitem sample in a JSF environment (notice how the flow 
                            definition is more concise because JSF takes care of data 
                            binding and validation).
                    </para>
    			</listitem>
    			<listitem>
                    <para>
                        <link linkend="phonebook-Portlet-sample">Phonebook-Portlet</link> - the 
                            phonebook sample in a Portlet environment (notice how the flow definitions do not change).
                    </para>
    			</listitem>
    		</orderedlist>
    	</para>
    </sect1>
    <sect1 id="running-samples">
    	<title>Running the Web Flow sample applications</title>
    	<para>
    		The samples can be built from the command line and imported as Eclipse projects - all samples come
    		with Eclipse project settings. It is also possible to start by importing the samples into Eclipse
    		first and then build with Ant within Eclipse.
    	</para>
    	<sect2>
    		<title>Building from the Command Line</title>
    		<para>
    			Java 1.5 (or greater) and Ant 1.6 (or greater) are prerequisites for building the sample applications.
    			Ensure those are present in the system path or are passed on the command line. To build Web Flow 
    			samples from the command line, open a prompt, cd to the directory where Spring Web Flow was
    			unzipped and run the following:
    			<programlisting>
cd projects/spring-webflow/build-spring-webflow
ant dist
				</programlisting>
				This builds all samples preparing "target" areas within each sample project subdirectory
				containing webapp structures in both exploded and WAR archive forms. The build also provides basic helper targets
				for deploying to Tomcat from Ant; however these webapp structures can be copied to any servlet container,
				and each project is also a Eclipse Dynamic Web Project (DWP) for easy deployment inside Eclipse 
				with the Eclipse Webtools Project (WTP).
    		</para>
    	</sect2>
    	<sect2>
    		<title>Importing Projects into Eclipse</title>
    		<para>
    			Importing the sample projects into Eclipse is easy. With a new or an existing workspace select:
    			<emphasis>File &gt; Import &gt; Existing Projects into Workspace</emphasis>. In the resulting dialog browse to the project
    			subdirectory where Spring Web Flow was unzipped and choose it as the root directory to import from.
    			Select OK. Here Eclipse will list all projects it found including the sample application projects.
    			Select the projects you're interested in, and select Finish.
    		</para>
    		<para>
    			If you previously built each project from the command line Eclipse will compile with no errors.
    			If not you will need to run the Ant build <emphasis>once</emphasis> for these errors to clear
    			and you can do that within Eclipse.
    		</para>
    		<para>
    			To build all projects inside Eclipse, import and expand the <literal>build-spring-webflow</literal> project, right-click on 
    			<literal>build.xml</literal> and select <emphasis>Run As &gt; Ant Build</emphasis>.
    			Doing this will run the default Ant target and will build all sample projects.
    		</para>
    		<para>
    			To build a single project inside Eclipse, simply select the project, right-click, and
    			select <emphasis>Run As &gt; Ant Build</emphasis>.  You can also use the convenient
    			shortcut ALT + SHIFT + X (Execute menu), then Q (Run Ant Build).
    		</para>
    		<para>
    			After Ant runs and the libraries needed to compile each project are downloaded,
    			all errors in the Eclipse problems view should go away. Try refreshing a project (F5)
    			if you still have errors.  In general, from this point on you no longer need Ant: you 
    			can rely on Eclipse's incremental compile and Eclipse's 	web tools (WTP) built-in JEE support
    			for deployment. (Ant is only needed in the system for command-line usage or when the list of
    			jar dependencies for a project changes and new jars need to be downloaded).
    		</para>
    	</sect2>
    	<sect2>
    		<title>Deploying projects inside Eclipse using Eclipse Web Tools (WTP)</title>
    		<para>
    			Each Spring Web Flow sample application project is a Eclipse Dynamic Web Project (DWP), 
    			for easy deployment to a server running inside the Eclipse IDE.  To take advantage 
    			of this, you must be running Eclipse 3.2 with Web Tools 1.5.
	    	</para>
	    	<para>
	    		To run a sample application as a webapp inside Eclipse, simply select the project, 
	    		right-click, and select <emphasis>Run -> Run On Server</emphasis>.  A convenient 
	    		shortcut for this action is ALT + SHIFT + X (Execute menu), R (Run on Server).
	    		The first time you do this you will be asked to setup a Server, where you are 
	    		expected to point Eclipse to a location where you have a Servlet Container
	    		such as Apache Tomcat installed.  Once your container has been setup and you finish the 
	    		deployment wizard, Eclipse will start the container and automatically publish 
	    		your webapp to it.  In addition, it will launch a embedded web browser allowing you
	    		to run the webapp fully inside the IDE.
	    	</para>
	    </sect2>
    	<sect2>
    		<title>Other IDE's</title>
    		<para>
    			Importing samples into other IDE's should be fairly straight-forward. If using another IDE
    			running the Ant build from the command line first may help as it will populate the lib
    			subdirectories of each sample project. Follow steps similar as those outlined for Eclipse above.
    		</para>
    	</sect2>
    </sect1>
    <sect1 id="fileupload-sample">
    	<title>Fileupload Example</title>
    	<sect2>
    		<title>Overview</title>
    		<para>
    			Fileupload is a simple one page web application for uploading files to a server. It is based
    			on Spring MVC, uses a Web Flow controller and one web flow with two states: a view state for
    			displaying the initial JSP page and an action state for processing the submit.	
    		</para>
    	</sect2>
    	<sect2>
    		<title>Web.xml</title>
    		<para>
    			The web.xml configuration maps requests for "*.htm" to the fileupload servlet - a regular
    			Spring MVC DispatcherServlet:
    			<programlisting>
&lt;servlet&gt;
	&lt;servlet-name&gt;fileupload&lt;/servlet-name&gt;
	&lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;
&lt;/servlet&gt;
	 
&lt;servlet-mapping&gt;
	&lt;servlet-name&gt;fileupload&lt;/servlet-name&gt;
	&lt;url-pattern&gt;*.htm&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
				</programlisting>
    		</para>
    	</sect2>
    	<sect2>
    		<title>Spring MVC Context</title>
    		<para>
    			The Spring MVC servlet context for the fileupload servlet (WEB-INF/fileupload-servlet.xml) defines
    			one controller bean:
    			<programlisting>
&lt;bean name="/admin.htm" class="org.springframework.webflow.executor.mvc.FlowController"&gt;
	&lt;property name="flowExecutor" ref="flowExecutor" /&gt;
&lt;/bean&gt;
				</programlisting>
				FlowController is a Web Flow controller. It is the main point of integration between Spring MVC
				and Spring Web Flow routing requests to one or more managed web flow executions. The
				FlowController is injected with flowExecutor and flowRegistry beans containing one web flow
				definition:
				<programlisting>
&lt;!-- Launches new flow executions and resumes existing executions. --&gt;
&lt;flow:executor id="flowExecutor" registry-ref="flowRegistry" repository-type="singlekey"/&gt;
	
&lt;!-- Creates the registry of flow definitions for this application --&gt;
&lt;flow:registry id="flowRegistry"&gt;
	&lt;flow:location path="/WEB-INF/fileupload.xml" /&gt;
&lt;/flow:registry&gt;
				</programlisting>
				Given the above definitions the following URI can be used to invoke the "fileupload" flow:
				<programlisting>
/swf-fileupload/admin.htm?_flowId=fileupload
				</programlisting>
    		</para>
    		<para>
    			Both flowExecutor and flowRegistry beans are defined with Spring custom tags schema available in
    			Spring 2.0. The custom tags make configuration less verbose and more readable. Regular Spring
    			bean definitions can be used as well with earlier versions of Spring.
    		</para>
    		<para>
				The Spring MVC context also defines a view resolver bean for resolving logical view names and a
				multipartResolver bean for the upload component. In general Web Flow does not aim to replace the
				flexibility of Spring MVC for view resolution. It focuses on the C in MVC.
    		</para>
    	</sect2>
    	<sect2>
    		<title>Fileupload Web Flow</title>
    		<para>
    			The start state for the fileupload flow (WEB-INF/fileupload.xml) is a view state:
    			<programlisting>
&lt;start-state idref="selectFile"/&gt;

&lt;view-state id="selectFile" view="fileForm"&gt;
	&lt;transition on="submit" to="uploadFile"/&gt;
&lt;/view-state&gt;
				</programlisting>
				View states allow a user to participate in a flow by presenting a suitable interface.
				The view attribute "fileForm" is a logical view name, which the Spring MVC view resolver bean
				will resolve to /WEB-INF/jsp/fileForm.jsp.
			</para>
			<para>
				The fileForm.jsp has an html form that submits back to the same controller
				(/swf-fileupload/admin.htm) and passes a "_flowExecutionKey" parameter.
				The value for _flowExecutionKey is provided by the FlowController - it identifies the current
				instance of the flow and allows Web Flow to resume flow execution, which is paused each time a
				view is displayed.
    		</para>
    		<para>
    			The name of the form submit button "_eventId_submit" indicates the event id to use for deciding
    			where to transition to next. Given an event with id of "submit" the "selectFile" view transitions
    			to the "uploadFile" state:
    			<programlisting>
&lt;action-state id="uploadFile"&gt;
	&lt;action bean="uploadAction" method="uploadFile"/&gt;
	&lt;transition on="success" to="selectFile"&gt;
		&lt;set attribute="fileUploaded" scope="flash" value="true"/&gt;
	&lt;/transition&gt;
	&lt;transition on="error" to="selectFile"/&gt;
&lt;/action-state&gt;
				</programlisting>
    		</para>
    		<para>
    			The "uploadFile" state is an action state. Action states integrate with business application code and
    			respond to the execution of that code by deciding what state of the flow to enter next. The code for the
    			uploadFile state is in the "uploadAction" bean declared in the Spring web context (/WEB-INF/fileupload-servlet.xml):
    			<programlisting>
&lt;bean id="uploadAction" class="org.springframework.webflow.samples.fileupload.FileUploadAction" /&gt;
				</programlisting>
				FileUploadAction has simple logic. It picks one of two Web Flow defined events - success or error,
				depending on whether the uploaded file size is greater than 0 or not. Both success and error
				transition back to the "selectFile" view state. However, a success event causes an attribute named
				"fileUploaded" to be set in flash scope
    		</para>
    		<para>
    			A flash-scoped attribute called "file" is also set programmatically in the FileUploadAction bean:
    			<programlisting>
context.getFlashScope().put("file", new String(file.getBytes()));
return success();
				</programlisting>
				This illustrates the choice to save attributes in one of several scopes either programatically or
				declaratively. 
    		</para>
    	</sect2>
    </sect1>
    <sect1 id="birthdate-sample">
    	<title>Birthdate Example</title>
    	<sect2>
    		<title>Overview</title>
    		<para>
    			Birthdate is a web application with 3 consequitive screens. The first two collect user input
    			to populate a form object. The third presents the results of business calculations based on
    			input provided in the first two screens.
    		</para>
    		<para>
    			Birthdate demonstrates Spring Web Flow's Struts integration as well as the use of FormAction,
    			a multi-action used to do the processing required for all three screens. The sample also uses JSTL
    			taglibs in conjunction with flows.
    		</para>
    	</sect2>
    	<sect2>
    		<title>Web.xml</title>
    		<para>
    			The web.xml configuration maps requests for "*.do" to a regular Struts ActionServlet:
    			<programlisting>
&lt;servlet&gt;
	&lt;servlet-name&gt;action&lt;/servlet-name&gt;
	&lt;servlet-class&gt;org.apache.struts.action.ActionServlet&lt;/servlet-class&gt;
&lt;/servlet&gt;
	 
&lt;servlet-mapping&gt;
	&lt;servlet-name&gt;action&lt;/servlet-name&gt;
	&lt;url-pattern&gt;*.do&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
				</programlisting>
				The web.xml also sets up the loading of a Spring context at web application startup:
				<programlisting>
&lt;context-param&gt;
	&lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
	&lt;param-value&gt;
		/WEB-INF/webflow-config.xml
	&lt;/param-value&gt;
&lt;/context-param&gt;

&lt;listener&gt;
	&lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
&lt;/listener&gt;
				</programlisting>
				The Spring web context contains beans to set up the Web Flow runtime environment. As will be
				shown in the next section Struts is configured with a Web Flow action that relies on the
				presence of a flowExecutor and a flowRegistry beans in this context.
    		</para>
    	</sect2>
    	<sect2>
    		<title>Struts Configuration</title>
    		<para>
    			The Struts configuration (WEB-INF/struts-config.xml) defines the following action mapping:
    			<programlisting>
&lt;action-mappings&gt;
	&lt;action path="/flowAction" name="actionForm" scope="request"
		type="org.springframework.webflow.executor.struts.FlowAction"/&gt;
&lt;/action-mappings&gt;
				</programlisting>
				FlowAction is a Struts action acting as a front controller to the Web Flow system routing Struts
				requests to one or more managed web flow executions. To fully configure the FlowAction a Spring
				web context is required to define flowExecutor and flowRegistry beans (named exactly so). This is
				an excerpt from the Spring web context (/WEB-INF/webflow-config.xml) defining these beans:
				<programlisting>
&lt;!-- Launches new flow executions and resumes existing executions. --&gt;	
&lt;flow:executor id="flowExecutor" registry-ref="flowRegistry"/&gt;
	
&lt;!-- Creates the registry of flow definitions for this application --&gt;
&lt;flow:registry id="flowRegistry"&gt;
	&lt;flow:location path="/WEB-INF/birthdate.xml"/&gt;
	&lt;flow:location path="/WEB-INF/birthdate-alternate.xml"/&gt;
&lt;/flow:registry&gt;
				</programlisting>
    		</para>
    		<para>
    			Based on the above, Web Flow is configured with two flows - birthdate and birthdate-alternate,
    			which can be invoked as follows:
    			<programlisting>
/swf-birthdate/flowAction.do?_flowId=birthdate
/swf-birthdate/flowAction.do?_flowId=birthdate-alternate
				</programlisting>
				The Struts configuration file also defines several global forwards: birthdateForm, cardForm,
				and yourAge, which will be referenced from Web Flow definitions as logical view names
				(and left to Struts to resolve to actual JSP pages). In general Web Flow does not aim to replace
				view resolution capabilities of web frameworks such as Struts or Spring MVC.
				It focuses on the C in MVC.
    		</para>
    	</sect2>
    	<sect2>
    		<title>Birthdate Web Flow</title>
    		<para>
    			The birthdate web flow (WEB-INF/birthdate.xml) defines the following start state:
    			<programlisting>
&lt;view-state id="enterBirthdate" view="birthdateForm"&gt;
	&lt;render-actions&gt;
		&lt;action bean="formAction" method="setupForm" /&gt;
	&lt;/render-actions&gt;
	&lt;transition on="submit" to="processBirthdateFormSubmit" /&gt;
&lt;/view-state&gt;
				</programlisting>
				The setupForm action is called to perform initializations for the enterBirthdate view state.
				Its action bean is defined the Spring web context WEB-INF/webflow-config.xml:
				<programlisting>
&lt;bean id="formAction" class="org.springframework.webflow.samples.birthdate.BirthDateFormAction" /&gt;
				</programlisting>
				BirthDateFormAction is a FormAction - it extends Web Flow's FormAction class, which serves a
				purpose similar to that of Spring MVC's SimpleFormController providing common form functionality
				for data binding and validation. 
    		</para>
    		<para>
    			When the BirthDateFormAction bean is instantiated it sets the name, class and scope of the form
    			object to use for loading form data upon display and collecting form data upon submit:
    			<programlisting>
public BirthDateFormAction() {
	// tell the superclass about the form object and validator we want to
	// use you could also do this in the application context XML ofcourse
	setFormObjectName("birthDate");
	setFormObjectClass(BirthDate.class);
	setFormObjectScope(ScopeType.FLOW);
	setValidator(new BirthDateValidator());
}
				</programlisting>
				The form object "birthDate" is placed in flow scope, which means it will not be re-created with
				each request but will be obtained from flow scope instead as long as the request remains within
				the same flow.
    		</para>
    		<para>
    			Once setupForm is done, the "birthdateForm" view will be rendered.
				The logical view name "birthdateForm" is a global-forward in struts-config.xml resolving to
				/WEB-INF/jsp/birthdateForm.jsp. This JSP collects data for the fields "name" and "date" bound to
				the birthDate form object and posts back to FlowAction with a submit image named
				"_eventId_submit". An event with the id of "submit" causes a transition to the
				processBirthdateFormSubmit action state defined as follows: 
				<programlisting>
&lt;action-state id="processBirthdateFormSubmit"&gt;
	&lt;action bean="formAction" method="bindAndValidate"&gt;
		&lt;attribute name="validatorMethod" value="validateBirthdateForm" /&gt;
	&lt;/action&gt;
	&lt;transition on="success" to="enterCardInformation" /&gt;
	&lt;transition on="error" to="enterBirthdate" /&gt;
&lt;/action-state&gt;
				</programlisting>
				The processBirthDateFormSubmit action state uses the same formAction bean as the one already used
				to setup the form. This time its bindAndValidate
				method is used to populate and validate the html form values. Also, note the "validateMethod"
				attribute used to specify the name of the method to invoke on the Validator object setup in the
				constructor of the BirthDateFormAction. The use of this attribute allows partial validation of
				complex objects populated over several consecutive screens.
    		</para>
    		<para>
    			On error the action returns to the view state it came from. On success it transitions to the
    			enterCardInformation view state:
    			<programlisting>
&lt;view-state id="enterCardInformation" view="cardForm"&gt;
	&lt;transition on="submit" to="processCardFormSubmit" /&gt;
&lt;/view-state&gt;
				</programlisting>
				The logical view name "cardForm" is a global-forward in struts-config.xml resolving to
				/WEB-INF/jsp/cardForm.jsp. This JSP collects data for the remaining fields of the birthDate form
				object - "sendCard" and "emailAddress", and posts back to FlowAction with a submit image named
				"_eventId_submit". An event with the id of "submit" causes a transition to the
				processCardFormSubmit action state defined as follows:
				<programlisting>
&lt;action-state id="processCardFormSubmit"&gt;
	&lt;action bean="formAction" method="bindAndValidate"&gt;
		&lt;attribute name="validatorMethod" value="validateCardForm" /&gt;
	&lt;/action&gt;
	&lt;transition on="success" to="calculateAge" /&gt;
	&lt;transition on="error" to="enterCardInformation" /&gt;
&lt;/action-state&gt;
				</programlisting>
				For this action state the bindAndValidate method of the formAction bean is used to populate and
				validate the remaining html form values. The "validateMethod" attribute specifies the name of the
				method to invoke on the Validator object specific to the fields loaded on the current screen.
    		</para>
    		<para>
    			On error the action returns to the view state it came from. On success it transitions to another
    			action state called calculateAge:
    			<programlisting>
&lt;action-state id="calculateAge"&gt;
	&lt;action bean="formAction" method="calculateAge" /&gt;
	&lt;transition on="success" to="displayAge" /&gt;
&lt;/action-state&gt;
				</programlisting>
				The logic for the calculateAge action state is in the calculateAge method of the same formAction
				bean used for data binding and validation. This demonstrates the flexibility Web Flow allows in
				properly structuring control and business logic according to function.
	 		</para>
	 		<para>
	 			The caculateAge method performs business calculations and adds a string in request scope with the
	 			calculated age. Upon successful completion the calculateAge action state transitions to the end
	 			view state:
	 			<programlisting>
&lt;end-state id="displayAge" view="yourAge" /&gt;
				</programlisting>
				Once again the logical view name "yourAge" is a global-forward in struts-config.xml resolving to
				/WEB-INF/jsp/yourAge.jsp. This JSP page retrieves the calculated age from request scope and
				displays the results for the user.
	 		</para>
	 		<para>
	 			The transition to the end state indicates the end of the web flow. The flow execution is cleaned up.
	 			If the web flow is entered again a new flow execution will start, creating a new form
	 			object named "birthDate" and placing it in flow scope.
	 		</para>
    	</sect2>
    	<sect2>
    		<title>Birthdate-alternate Web Flow</title>
    		<para>
    			The birthdate-alternate web flow (/WEB-INF/birthdate-alternate.xml) offers an alternative way and
    			more compact way of defining the same web flow. For example the birthdate web flow defines two
    			independent states for the first screen - a view state (enterBirthdate) and an action state
    			(processBirthdateFormSubmit). In birthdate-alternate those are encapsulated in the view state
    			enterBirthdate as follows:
    			<programlisting>
&lt;view-state id="enterBirthdate" view="birthdateForm"&gt;
	&lt;render-actions&gt;
		&lt;action bean="formAction" method="setupForm" /&gt;
	&lt;/render-actions&gt;
	&lt;transition on="submit" to="enterCardInformation"&gt;
		&lt;action bean="formAction" method="bindAndValidate"&gt;
			&lt;attribute name="validatorMethod" value="validateBirthdateForm" /&gt;
		&lt;/action&gt;
	&lt;/transition&gt;
&lt;/view-state&gt;
				</programlisting>
				Here the setupForm action state is defined as a render-action of the enterBirthdate view state
				while the transition to the next screen uses a nested action bean invoked before the transition
				occurs. Notice that success is implicitly required for the transition to occur. Similarly on error
				the transition does not occur and the same view state is displayed again.
    		</para>
    		<para>
    			The second screen is also defined with a nested transition and action bean:
    			<programlisting>
&lt;view-state id="enterCardInformation" view="cardForm"&gt;
	&lt;transition on="submit" to="calculateAge"&gt;
		&lt;action bean="formAction" method="bindAndValidate"&gt;
			&lt;attribute name="validatorMethod" value="validateCardForm" /&gt;
		&lt;/action&gt;
	&lt;/transition&gt;
&lt;/view-state&gt;
				</programlisting>
				The remaining two states - calculateAge and displayAge are identical.
    		</para>
    	</sect2>
    </sect1>
    <sect1 id="shippingrate-sample">
        <title>Shippingrate Example</title>
        <sect2>
            <title>Overview</title>
            <para>
                The Shippingrate sample demonstrates the use of Spring Web Flow in combination with 
                Ajaxian techniques. It consists of several wizard-style steps executed 
                with Ajax requests and refreshing a portion of the page.
                The input is collected from the user in incremental steps. It is stored 
                in a flow-scoped object and is then used to calcualte a shipping rate.
                The example also demonstrates invocation of a service-layer bean
                defined in a Spring context to perform calculations and
                to provide reference data such as countries and package types.
            </para>
        </sect2>
        <sect2>
            <title>Web.xml</title>
            <para>
                The web.xml configuration maps requests for "*.htm" to the 
                shippingrate servlet - a regular Spring MVC DispatcherServlet:
                <programlisting>
&lt;servlet&gt;
    &lt;servlet-name&gt;shippingrate&lt;/servlet-name&gt;
    &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;
&lt;/servlet&gt;

&lt;servlet-mapping&gt;
    &lt;servlet-name&gt;shippingrate&lt;/servlet-name&gt;
    &lt;url-pattern&gt;*.htm&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
                </programlisting>
                The web.xml also ensures the following Spring context file is loaded 
                at runtime from the web application classpath:
                <programlisting>
&lt;context-param&gt;
    &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
    &lt;param-value&gt;
        classpath:org/springframework/webflow/samples/shippingrate/domain/services.xml
    &lt;/param-value&gt;
&lt;/context-param&gt;
                </programlisting>
                The services.xml Spring context defines a "rateService" bean providing 
                operations for making shipping rate calculations and for retrieving 
                reference data required for display in the JSP pages of the application.
            </para>
        </sect2>
        <sect2>
            <title>Spring MVC Context</title>
            <para>
                The Spring MVC servlet context for the shippingrate servlet (WEB-INF/shippingrate-servlet.xml) 
                defines one controller bean:
                <programlisting>
&lt;bean name="/rates.htm" class="org.springframework.webflow.executor.mvc.FlowController"&gt;
    &lt;property name="flowExecutor" ref="flowExecutor" /&gt;
&lt;/bean&gt;
                </programlisting>
                FlowController is a Web Flow controller. It is the main point of integration between Spring MVC
                and Spring Web Flow routing requests to one or more managed web flow executions. The
                FlowController is injected with flowExecutor and flowRegistry beans:
                <programlisting>
&lt;!-- Launches new flow executions and resumes existing executions. --&gt;
&lt;flow:executor id="flowExecutor" registry-ref="flowRegistry" repository-type="simple"/&gt;
    
&lt;!-- Creates the registry of flow definitions for this application --&gt;
&lt;flow:registry id="flowRegistry"&gt;
    &lt;flow:location path="/WEB-INF/flows/**/*-flow.xml" /&gt;
&lt;/flow:registry&gt;
                </programlisting>
                The flowExecutor and the flowRegistry beans collectively configure
                the FlowController with one web flow - the getRate-flow defined in
                /WEB-INF/flows/getRate-flow.xml. The flowExecutor uses a "simple"
                repository, which manages execution state in the user session.
            </para>
            <para>
                Given the above definitions the following URI  can be used to initiate 
                the getRate-flow:
                <programlisting>
/swf-shippingrate/rates.htm?_flowId=getRate-flow
                </programlisting>
            </para>
        </sect2>
        <sect2>
            <title>Ajax Requests</title>
            <para>
                The shippingrate example consists of several wizard-style steps.
                After the initial index.jsp subsequent pages are 
                loaded in an Ajax manner without reloading the entire page.
            </para>
            <warning>
                <para>
                    This sample has been tested successfully on Internet Explorer 6 and 7, 
                    Firefox 2.0, and Safari 2. There are known Javascript issues 
                    with use on Firefox 1.5.
                </para>
            </warning>
            <para>
                The Ajax requests are done with the help of the
                <ulink url="http://prototype.conio.net">Prototype</ulink>
                framework and a thin JavaScript layer over it providing
                convenient functions for processing Ajax form and get requests.
                The required Javascript libraries are included in index.jsp as follows:
                <programlisting>
&lt;script src="prototype.js" type="text/javascript"&gt;&lt;/script&gt;
&lt;script src="swf_ajax.js" type="text/javascript"&gt;&lt;/script&gt;
                </programlisting>
            </para>
            <para>
                When index.jsp is loaded the following JavaScript invokes the getRate-flow
                and replaces the content of the getRateWizard div tag with the response
                returned from the server:
                <programlisting>
&lt;div id="getRateWizard"&gt;
    &lt;script type="text/javascript"&gt;
    window.onload = function() {
        new SimpleRequest('getRateWizard', 'rates.htm', 'get', '_flowId=getRate-flow');
    };
    &lt;/script&gt;
&lt;/div&gt;
                </programlisting>
                Functions are first-class citizens and a type in JavaScript. 
                The script above creates an instance of
                the SimpleRequest function defined in swf_ajax.js. This function invokes
                Prototype's Ajax.Updater with the specified URL and request parameters. On success
                the content of the getRateWizard div is replaced with the response returned
                from the server. On failure such as an HTTP response code other 200 (OK) 
                an error message is displayed.
            </para>
            <para>
                The next few pages are form-based JSP's - selectCustomer.jsp, selectReceiver.jsp, 
                etc. Each of them contains the following JavaScript call at the bottom:
                <programlisting>
&lt;script type="text/javascript"&gt;
    formRequest('selectCustomerTypeForm');
&lt;/script&gt;
                </programlisting>
                The formRequest function is also defined in swf_ajax.js 
                and it uses Prototype to register a handler for the form submit event:
                <programlisting>
function formRequest(formElementId) {
    Event.observe(formElementId, 'submit', handleSubmitEvent, true);
}
                </programlisting>
                The handleSubmitEvent function extracts the form parameters, stops the 
                submit event, and posts an AJAX request via XMLHttpRequest. On success
                the results returned form the server replace the content of the form.
                On failure such as an HTTP response code other 200 (OK) an error 
                message is displayed.
            </para>
            <para>
                Although not demonstrated in this example a back button can be 
                implemented in parallel with the Next button used to advance from
                one screen to the next. This would be necessary because the browser
                back button - a common issue in Ajax applications, contrary to user
                expectation returns to the page prior to the first Ajax request.
            </para>
            <para>
                As a result of the Ajax requests the entire wizard is able to 
                function within a portion of the page without refresing 
                the remaining information on it.
            </para>
        </sect2>
        <sect2>
            <title>getRate Web Flow</title>
            <para>
                The getRate-flow (/WEB-INF/jsp/flows/getRate-flow.xml) defines the following start state:
                <programlisting>
&lt;view-state id="selectCustomerType" view="selectCustomer"&gt;
    &lt;transition on="submit" to="selectSender"&gt;
        &lt;action bean="formAction" method="bind" /&gt;
    &lt;/transition&gt;
&lt;/view-state&gt;
                </programlisting>
                This is a view state, which will display the initial form using the 
                JSP page /WEB-INF/jsp/selectCustomer.jsp. Notice, the use of a start action 
                executed immediately before the JSP is displayed:
                <programlisting>
&lt;start-actions&gt;
    &lt;action bean="formAction" method="setupForm" /&gt;
&lt;/start-actions&gt;
                </programlisting>                
                The "formAction" bean is defined in the Spring servlet context 
                (/WEB-INF/shippingrate-servlet.xml). It specifies a form object
                and  a validator to use for form data binding and validation:
                <programlisting>
&lt;!-- Performs "form backing object" data binding and validation on input submit --&gt;
&lt;bean id="formAction" class="org.springframework.webflow.action.FormAction"&gt;
    &lt;property name="formObjectName" value="rateCriteria" /&gt;
    &lt;property name="formObjectClass" value="org.springframework.webflow.samples.shippingrate.domain.RateCriteria" /&gt;
    &lt;property name="formObjectScope" value="FLOW" /&gt;
    &lt;property name="validator"&gt;
        &lt;bean class="org.springframework.webflow.samples.shippingrate.domain.RateCriteriaValidator" /&gt;
    &lt;/property&gt;
&lt;/bean&gt;
                </programlisting>
                The form object of type RateCriteria will be used to collect data 
                from the user in several steps. The form object will be stored in FLOW scope
                and will not be re-created with each request as long 
                as the flow hasn't reached its end state. The actual binding of
                html form fields to the RateCriteria object is based on
                Spring's data binding mechanism. Html form fields are surrounded
                with the &lt;spring:bind&gt; tag containing the path 
                nested property field. FormAction's bindAndValidate method
                will initiate the actual binding on the server side 
                between HTTP request parameters and RateCriteria data fields.
            </para>
            <para>
                When the selectCustomer.jsp submits back to the FlowController via
                "/swf-shippingrate/rate.htm" it uses a submit button named 
                "_eventId_submit". This indicates to Web Flow a transition to 
                the "selectSender" view state. This view state is defined as follows:
                <programlisting>
&lt;view-state id="selectSender" view="selectSender"&gt;
    &lt;render-actions&gt;
        &lt;bean-action bean="rateService" method="getCountries"&gt;
            &lt;method-result name="countries" /&gt;
        &lt;/bean-action&gt;
    &lt;/render-actions&gt;
    &lt;transition on="submit" to="selectReceiver"&gt;
        &lt;action bean="formAction" method="bindAndValidate"&gt;
            &lt;attribute name="validatorMethod" value="validateSender" /&gt;
        &lt;/action&gt;
    &lt;/transition&gt;
&lt;/view-state&gt;
                </programlisting>
                The selectSender view state has a render action: 
                the "rateService" bean that was loaded through the services.xml context referenced
                in web.xml. The purpose of the render action is to load data required 
                to render the JSP. In this case the rateService bean has a method called
                getCountries that returns a list of countries to be displayed in a drop-down
                by the JSP.
            </para>
            <para>
                The "selectSender" view state also defines one transition: on event with 
                id of "submit" a transition to the "selectReceiver" view state occurs. 
                A pre-requisite for the transition to occur is the successful completion of 
                formAction bean's bindAndValidate method. The attribute "validatorMethod" on
                the bean specifies the name of the method to invoke on the Validator object 
                specifically for the fields of the current screen. 
                If the bindAndValidate method does not succeed the transition does not take
                place and the flow remains in the "selectSender" view 
                state where the user can review the errors and modify the selection.
            </para>
            <para>
                The next two states in the flow - selectReceiver and selectPackageDetails use similar 
                mechnisms. The rateSevice bean is used to retrieve countries and package types for 
                use in the JSP. The form backing object RateCriteria stored in FLOW scope 
                is used to collect user input with each form submit. 
            </para>
            <para>
                The "findRate" action state occurs after all user input has been provided. 
                It is defined as follows:
                <programlisting>
&lt;action-state id="findRate"&gt;
    &lt;bean-action bean="rateService" method="getRate"&gt;
        &lt;method-arguments&gt;
            &lt;argument expression="flowScope.rateCriteria" /&gt;
        &lt;/method-arguments&gt;
        &lt;method-result name="rate" /&gt;
    &lt;/bean-action&gt;
    &lt;transition on="success" to="showRate" /&gt;
&lt;/action-state&gt;
                </programlisting>
                Logic for the action state is provided by the getRate method of 
                the rateService bean. The RateCriteria object stored in FLOW scope
                and containing the user input is passed to the rateService bean.
                The result of the method is exposed in request scope under 
                the name "rate". 
            </para>
            <para>
                The next and final state "showRate" is a JSP page, which accesses the calculated rate 
                information and displays it to the user.
            </para>            
        </sect2>
    </sect1>    
    <sect1 id="numberguess-sample">
        <title>Numberguess Example</title>
        <sect2>
            <title>Overview</title>
            <para>
                Numberguess uses Web Flow to implement two number guessing games.
                For each game the user can enter multiple guesses and depending 
                on the answer either transition back to the same screen or 
                advance to the final screen. Logic for the guessing games is 
                provided through FLOW-scoped beans, which also maintain state
                such as the total number of guesses. The example defines transitions 
                using event pattern matching and custom exception handlers.
            </para>
        </sect2>
        <sect2>
            <title>Web.xml</title>
            <para>
                The web.xml configuration maps "*.htm" requests to the numberguess servlet - 
                a regular Spring MVC DispatcherServlet:
                <programlisting>
&lt;servlet&gt;
    &lt;servlet-name&gt;numberguess&lt;/servlet-name&gt;
    &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;
    &lt;init-param&gt;
        &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
        &lt;param-value&gt;/WEB-INF/dispatcher-servlet.xml&lt;/param-value&gt;
    &lt;/init-param&gt;
&lt;/servlet&gt;

&lt;servlet-mapping&gt;
    &lt;servlet-name&gt;numberguess&lt;/servlet-name&gt;
    &lt;url-pattern&gt;*.htm&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
                </programlisting>
                The Spring web context is loaded from a file called 
                /WEB-INF/dispatcher-servlet.xml.
            </para>
        </sect2>
        <sect2>
            <title>Spring MVC Context</title>
            <para>
                The Spring MVC web context (WEB-INF/dispatcher-servlet.xml) 
                defines one controller bean:
                <programlisting>
&lt;bean name="/play.htm" class="org.springframework.webflow.executor.mvc.FlowController"&gt;
    &lt;property name="flowExecutor" ref="flowExecutor" /&gt;
&lt;/bean&gt;
                </programlisting>
                FlowController is a Web Flow controller. It is the main point of 
                integration between Spring MVC and Spring Web Flow routing requests 
                to one or more managed web flow executions. The FlowController is 
                injected with flowExecutor and flowRegistry beans:
                <programlisting>
&lt;!-- Launches new flow executions and resumes existing executions. --&gt;
&lt;flow:executor id="flowExecutor" registry-ref="flowRegistry" repository-type="singlekey"/&gt;
    
&lt;!-- Creates the registry of flow definitions for this application --&gt;
&lt;flow:registry id="flowRegistry"&gt;
    &lt;flow:location path="/WEB-INF/higherlower.xml" /&gt;
    &lt;flow:location path="/WEB-INF/mastermind.xml" /&gt;
&lt;/flow:registry&gt;
                </programlisting>
                The flowExecutor and the flowRegistry beans collectively configure
                the FlowController with two web flows - higherlower and mastermind.
                This flowExecutor is configured with a simple repository that assigns 
                a single flow execution key per conversation. The key, once assigned, 
                never changes for the duration of the conversation. 
            </para>
            <para>
                Given the above definitions the following URI's can be used to initiate 
                each of the two flows:
                <programlisting>
/swf-numberguess/play.htm?_flowId=higherlower
/swf-numberguess/play.htm?_flowId=mastermind
                </programlisting>
            </para>
            <para>
                The Spring MVC servlet context also defines a view resolver bean for 
                resolving logical view names. In general Web Flow does not aim 
                to replace the flexibility of Spring MVC for view resolution. 
                It focuses on the C in MVC.
            </para>
        </sect2>
        <sect2>
            <title>Higherlower Flow</title>
            <para>
                The Higherlower flow (/WEB-INF/higherlower.xml) starts with the following 
                flow variable declaration:
                <programlisting>
&lt;var name="game" class="org.springframework.webflow.samples.numberguess.HigherLowerGame"/&gt;
                </programlisting>
                This variable is automatically created when an execution of the flow
                begins and will exist in FLOW scope throughout its duration.
            </para>
            <para>
                The start state for the flow is defined as follows:
                <programlisting>
&lt;view-state id="enterGuess" view="higherlower.enterGuess"&gt;
    &lt;transition on="submit" to="makeGuess"/&gt;
&lt;/view-state&gt;
                </programlisting>
                The view resolver bean of Spring MVC will resolve "higherlower.enterGuess" 
                to /WEB-INF/jsp/higherlower.enterGuess.jsp.
                This JSP has a form with one input field for the guess number.
                The "game" variable referenced throughout the JSP 
                is the FLOW-scoped variable that was declared at the top of 
                the flow definition.
            </para>
    	    <para>
        		The name of the form submit button "_eventId_submit" indicates the 
                event id to use for deciding where to transition to next. Given an 
                event with id of "submit" the "enterGuess" view state transitions
    			to the "makeGuess" action state defined as follows:
                <programlisting>
&lt;action-state id="makeGuess"&gt;
    &lt;evaluate-action expression="flowScope.game.makeGuess(requestParameters.guess)"&gt;
        &lt;evaluation-result name="guessResult"/&gt;
    &lt;/evaluate-action&gt;
    &lt;transition on="CORRECT" to="showAnswer"/&gt;
    &lt;transition on="*" to="enterGuess"/&gt;
    &lt;transition on-exception="java.lang.NumberFormatException" to="enterGuess"/&gt;
&lt;/action-state&gt;
                </programlisting>
            </para>
            <para>
                The makeGuess action state consists of one evaluate action and three
                transitions. Evaluate actions are used to invoke logic encapsulated
                in a FLOW-scoped object - in this case the game bean. 
                The makeGuess method of the game bean returns one of several enum 
                values it defines:
                <programlisting>
enum GuessResult {
    TOO_HIGH, TOO_LOW, CORRECT, INVALID
}
                </programlisting>
                Web Flow detects the returned result from the makeGuess method
                is a JDK 1.5 enum type and 
                creates an Event with a String id matching the enum value. If the
                makeGuess method returns CORRECT a transition to the final 
                showAnswer state occurs. For any other event (defined with the event 
                pattern on="*") Web Flow returns to the enterGuess 
                state. The makeGuess state also defines one on-exception transition
                demonstrating how specific Exceptions can be incorporated into
                flow transition logic.
            </para>
            <para>
                The end-state showAnswer resolves to the JSP page 
                /WEB-INF/jsp/higherlower.showAnswer.jsp, which simply shows the
                correct guess. At this point the flow has ended and the "game" bean 
                is no longer in scope.
            </para>
        </sect2>
        <sect2>
            <title>Mastermind Flow</title>
            <para>
                The mastermind flow uses a similar flow definition to implement a 4-digit
                guessing game:
                <programlisting>
&lt;var name="game" class="org.springframework.webflow.samples.numberguess.MastermindGame"/&gt;

&lt;start-state idref="enterGuess"/&gt;

&lt;view-state id="enterGuess" view="mastermind.enterGuess"&gt;
    &lt;transition on="submit" to="makeGuess"/&gt;
&lt;/view-state&gt;

&lt;action-state id="makeGuess"&gt;
    &lt;evaluate-action expression="flowScope.game.makeGuess(requestParameters.guess)"&gt;
        &lt;evaluation-result name="guessResult"/&gt;
    &lt;/evaluate-action&gt;
    &lt;transition on="CORRECT" to="showAnswer"/&gt;
    &lt;transition on="*" to="enterGuess"/&gt;
&lt;/action-state&gt;

&lt;end-state id="showAnswer" view="mastermind.showAnswer"/&gt;
                </programlisting>
                The MastermindGame class encapsulates the logic for the game and 
                is stored as a FLOW-scoped bean. 
                It returns one of three possible enum values -
                WRONG, CORRECT, or INVALID, which Web Flow converts to events with 
                id's matching the enum values. If the guess is INVALID the JSP page
                /WEB-INF/jsp/mastermind.enterGuess.jsp will print an error message.
                If the guess is CORRECT the flow will transition to the showAnswer 
                end state and complete the flow.
            </para>
        </sect2>
    </sect1>    
    <sect1 id="flowlauncher-sample">
        <title>Flowlauncher Example</title>
        <sect2>
            <title>Overview</title>
            <para>
                Flowlauncher demonstrates two different ways one web flow can launch 
                another - by redirecting to it or by launching it as a subflow. 
                Flowlauncher has two flows: Sample A and Sample B. As a root level 
                flow Sample A either transitions to B through a subflow state or 
                redirects to B in its end state.
            </para>
        </sect2>
        <sect2>
            <title>Web.xml</title>
            <para>
                The web.xml configuration maps "*.htm" requests to the flowlauncher servlet - 
                a regular Spring MVC DispatcherServlet:
                <programlisting>
&lt;servlet&gt;
    &lt;servlet-name&gt;flowlauncher&lt;/servlet-name&gt;
    &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;
&lt;/servlet&gt;

&lt;servlet-mapping&gt;
    &lt;servlet-name&gt;flowlauncher&lt;/servlet-name&gt;
    &lt;url-pattern&gt;*.htm&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
                </programlisting>
            </para>
        </sect2>    
        <sect2>
            <title>Spring MVC Context</title>
            <para>
                The Spring MVC web context (WEB-INF/flowlauncher-servlet.xml) defines one controller bean:
                <programlisting>
&lt;bean name="/flowController.htm" class="org.springframework.webflow.executor.mvc.FlowController"&gt;
    &lt;property name="flowExecutor" ref="flowExecutor" /&gt;
&lt;/bean&gt;
                </programlisting>
                FlowController is a Web Flow extension of Spring MVC's AbstractController. 
                It contains a FlowExecutor and directs incoming requests for one
                or more managed flow executions to it. The FlowExecutor bean is configured 
                in the same context:
                <programlisting>
&lt;!-- Launches new flow executions and resumes existing executions. --&gt;
&lt;flow:executor id="flowExecutor" registry-ref="flowRegistry"/&gt;

&lt;!-- Creates the registry of flow definitions for this application --&gt;
&lt;flow:registry id="flowRegistry"&gt;
    &lt;flow:location path="/WEB-INF/sampleA.xml" /&gt;
    &lt;flow:location path="/WEB-INF/sampleB.xml" /&gt;
&lt;/flow:registry&gt;
                </programlisting>
                A single FlowController may direct all flows for an application serving as
                a gateway to Web Flow. Based on the above definitions the flows
                sampleA and sampleB can be invoked as follows:
                <programlisting>
/swf-flowlauncher/flowController.htm?_flowId=sampleA
/swf-flowlauncher/flowController.htm?_flowId=sampleB
                </programlisting>
                The welcome index.html file for the web application invokes
                the flows and passes additional input using either a URL link 
                or a form submit.
            </para>
        </sect2>    
        <sect2>
            <title>Sample A Web Flow</title>
            <para>
                The Sample A web flow (/WEB-INF/sampleA.xml) begins with an input mapping declaration:
                <programlisting>
&lt;input-mapper&gt;
    &lt;mapping source="input" target="flowScope.input" /&gt;
&lt;/input-mapper&gt;
                </programlisting>
                This declaration reads "when a new execution of this flow starts map the 
                input attribute named <emphasis>input</emphasis> into a flowScope attribute
                also named input". Spring Web Flow will automatically provide the request
                parameters as input to the flow when launching a new flow execution.
                Following this declaration the <emphasis>input</emphasis>
                request parameter will remain available for the duration of the flow. 
            </para>
            <para>
                There are 3 states in this flow: the start state, the end state, and a subflow 
                state. The start state is a view state - it will display a JSP page and allow
                the user to make a choice. The subflow state initiates Sample B as a 
                subflow of the current flow - subflows give the ability to compose independent
                modules together to compose complex controller workflows. And the end state 
                launches Sample B by redirecting to it.
            </para>
            <para>
                The subflow state launches B with the following input attribute declaration.
                This declaration reads "pass the value of the flow-scoped attribute named
                <emphasis>input</emphasis> as an attribute also named <emphasis>input</emphasis>
                to subflow B. 
                <programlisting>
&lt;attribute-mapper&gt;
    &lt;input-mapper&gt;
        &lt;mapping source="flowScope.input" target="input" /&gt;
    &lt;/input-mapper&gt;
&lt;/attribute-mapper&gt;
                </programlisting>
                The next line is a transition defining how to respond 
                when the subflow ends: advance back to the start state for Sample A.
                <programlisting>
&lt;transition on="end" to="aPage" /&gt;
                </programlisting>
            </para>
            <para>
                The end state demonstrates how to redirect to Sample B upon completion of 
                the root level flow Sample A:
                <programlisting>
&lt;end-state id="endAndLaunchB" view="flowRedirect:sampleB?input=${requestParameters.input}" /&gt;
                </programlisting>
                This declaration causes A to be terminated and B to start
                with the given requst input parameter.
            </para>
        </sect2>
        <sect2>
            <title>Sample B Web Flow</title>
            <para>
                The flow Sample B (/WEB-INF/sampleB.xml) - used as a subflow in Sample A has two 
                simple states: a view state and an end state. From the view state "bPage" the
                flow transitions to the end state:
                <programlisting>
&lt;view-state id="bPage" view="bPage"&gt;
    &lt;transition on="end" to="end" /&gt;
&lt;/view-state&gt;

&lt;end-state id="end" /&gt;
                </programlisting>
                The "id" attribute of the end state matches the "on" attribute of the
                transition in the outer flow's subflow state, which the outer flow 
                uses to resume itself.
            </para>
            <para>
                Also notice how bPage.jsp makes a check to detect if Sample B is 
                running as a subflow of Sample A or if it is running as a top-level flow:
                <programlisting>
&lt;c:if test="${!flowExecutionContext.activeSession.root}"&gt;
                </programlisting>
            </para>
            The FlowExecutionContext object is exposed to the views (JSPs)
            to make information like this available during response rendering.
        </sect2>    
    </sect1>
    <sect1 id="itemlist-sample">
        <title>Iitemlist Example</title>
        <sect2>
            <title>Overview</title>
            <para>
                Itemlist demonstrates how to configure a FlowExecutor with an argument handler
                enabling it to process REST-style requests where the name of the target
                flow is in the URL instead of a _flowId request parameter.
                The example also demonstrates inner flows as well as how an output parameter 
                can be passed from a subflow to a parent flow.
                Finally, it serves as an illustration of how to configure Spring Web Flow
                using classic Spring 1.x bean definitions.
            </para>
        </sect2>
        <sect2>
            <title>Web.xml</title>
            <para>
                The web.xml configuration maps "/app/*" requests to the itemlist servlet - 
                a regular Spring MVC DispatcherServlet:
                <programlisting>
&lt;servlet&gt;
    &lt;servlet-name&gt;itemlist&lt;/servlet-name&gt;
    &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;
&lt;/servlet&gt;

&lt;servlet-mapping&gt;
    &lt;servlet-name&gt;itemlist&lt;/servlet-name&gt;
    &lt;url-pattern&gt;/app/*&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
                </programlisting>
            </para>
        </sect2>
        <sect2>
            <title>Spring MVC Context</title>
            <para>
                The Spring MVC web context (/WEB-INF/itemlist-serlvet.xml) defines one controller
                and one URL handler mapping:
                <programlisting>
&lt;bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"&gt;
    &lt;property name="alwaysUseFullPath" value="true" /&gt;
    &lt;property name="mappings"&gt;
        &lt;value&gt;/app/**/**=flowController&lt;/value&gt;
    &lt;/property&gt;
&lt;/bean&gt;

&lt;bean id="flowController" class="org.springframework.webflow.executor.mvc.FlowController"&gt;
    &lt;property name="flowExecutor" ref="flowExecutor" /&gt;
    &lt;property name="argumentHandler"&gt;
        &lt;bean class="org.springframework.webflow.executor.support.RequestPathFlowExecutorArgumentHandler" /&gt;
    &lt;/property&gt;
&lt;/bean&gt;
                </programlisting>
                All requests with a servlet path matching "/app/**/**" are mapped to the "flowController" bean.
                The FlowController is a Web Flow extension of Spring MVC's AbstractController delegating
                requests to one or more managed web flows. It acts as gateway to Web Flow defined control 
                logic and a single instance can serve the application.
            </para>
            <para>
                The usual way to launch a specific web flow is to pass the _flowId request parameter.
                However, this example is configured with a RequestPathFlowExecutorArgumentHandler 
                for processing REST-style URL's. 
                Requests for services built around the REST concept are encoded in the URL 
                and not as query string parameters. The way to invoke a web flow with 
                this argument handler is to follow:
                <programlisting>
http://${host}/${context path}/${dispatcher path}/${flowId}
                </programlisting>
            </para>
            <para>
                The FlowController is configured with a flowExecutor and flowRegistry beans containing 
                two web flows - itemlist and itemlist-alternate:
                <programlisting>
&lt;!-- Launches new flow executions and resumes existing executions: Spring 1.2 config version --&gt;
&lt;bean id="flowExecutor" class="org.springframework.webflow.config.FlowExecutorFactoryBean"&gt;
    &lt;property name="definitionLocator" ref="flowRegistry"/&gt;
&lt;/bean&gt;

&lt;!-- Creates the registry of flow definitions for this application: Spring 1.2 config version --&gt;   
&lt;bean id="flowRegistry" class="org.springframework.webflow.engine.builder.xml.XmlFlowRegistryFactoryBean"&gt;
    &lt;property name="flowLocations"&gt;
        &lt;list&gt;
            &lt;value&gt;/WEB-INF/itemlist.xml&lt;/value&gt;
            &lt;value&gt;/WEB-INF/itemlist-alternate.xml&lt;/value&gt;
        &lt;/list&gt;
    &lt;/property&gt;
&lt;/bean&gt;
                </programlisting>
                The FlowRegistry and FlowExecutor are defined with Spring 1.2 compatible bean definitions.
                However, starting with Spring 2.0 Web Flow also offers the 
                custom tags flow:registry and flow:executor, which are more 
                readable and less verbose.
            </para>
            <para>
                Based on the above web context definition use the following URL's to invoke 
                the itemlist or the itemlist-alternate web flows:
                <programlisting>
/swf-itemlist/app/itemlist
/swf-itemlist/app/itemlist-alternate                
                </programlisting>
            </para>
            <para>    
                Also defined in itemlist-servlet.xml are three "action" beans - createItemAction, 
                addItemAction, and mapItemAction, which will be referenced from action states 
                in the web flow definitions.
            </para>
        </sect2>
        <sect2>
            <title>Itemlist Web Flow</title>
            <para>
                The itemlist flow allows adding items to a list. There are
                two view states - displayItemList and displayItem, and two action states - 
                createItem and addItem. 
            </para>
            <para>
                The displayItemList view state resolves to /WEB-INF/jsp/itemList.jsp, which 
                lists all items on the list and displays an "Add" button with the 
                name "_eventId_add". The name of the button indicates the 
                event id to use for deciding where to transition to next. 
                Also, notice that instead of posting a "_flowId" parameter
                the JSP sets the form action to the value of flowExecutionKey -
                a value automatically made available in the page 
                context by Web Flow:
                <programlisting>
&lt;form action="${flowExecutionKey}" method="post"/&gt;
                </programlisting>
            </para>
            <para>
                When the form submits an event with the "_eventId_add" button
                the displayItemList view state transitions to the 
                createItem action state. 
                <programlisting>
&lt;view-state id="displayItemlist" view="itemlist"&gt;
    &lt;transition on="add" to="createItem" /&gt;
&lt;/view-state&gt;

&lt;action-state id="createItem"&gt;
    &lt;action bean="createItemAction" /&gt;
    &lt;transition on="success" to="displayItem" /&gt;
&lt;/action-state&gt;
                </programlisting>                
            </para>
            <para>
                The "createItemAction" bean is declared in the Spring MVC context 
                (/WEB-INF/itemlist-servlet.xml). It simply returns "success", which 
                causes a transition to the displayItem view state.
            </para>
            <para>
                The next two states displayItem and addItem allow adding an item to the
                list variable declared at the top of the flow:
                <programlisting>
&lt;var name="list" class="java.util.ArrayList" /&gt;
                </programlisting>
                The "addItemAction" bean is also declared in the Spring MVC context.
                It performs the add by accessing the list in flow scope and 
                the item to be added from the request parameters as follows:
                <programlisting>
Collection list = context.getFlowScope().getRequiredCollection("list");
String data = context.getRequestParameters().get("data");
if (data != null &amp;&amp; data.length() > 0) {
    list.add(data);
}
                </programlisting>
                For any outcome the addItem state transitions back to the initial
                displayItemList state using an event pattern match:
                <programlisting>
&lt;action-state id="addItem"&gt;
    &lt;action bean="addItemAction" /&gt;
    &lt;transition on="*" to="displayItemlist" /&gt;
&lt;/action-state&gt;
                </programlisting>
            </para>
        </sect2>
        <sect2>
            <title>Itemlist-alternate Web Flow</title>
            <para>
                The Itemlist-alternate web flow (/WEB-INF/itemlist-alternate.xml) 
                has functionality equivalent  to that of itemlist but instead uses
                a subflow for selecting individual items.
                The "addItem" state is a subflow state 
                invoking an inline flow called "item" (also defined in itemlist-alternate.xml)
                accepting an output parameter from the subflow and adding the
                output parameter to a flow-scoped list variable:
                <programlisting>
&lt;subflow-state id="addItem" flow="item"&gt;
    &lt;attribute-mapper&gt;
        &lt;output-mapper&gt;
            &lt;mapping source="item" target-collection="flowScope.list" /&gt;
        &lt;/output-mapper&gt;
    &lt;/attribute-mapper&gt;
    &lt;transition on="finish" to="displayItemlist" /&gt;
&lt;/subflow-state&gt;
                </programlisting>
                An output-mapper is used to pass results from a subflow to a parent flow.
                The above declaration defines an expectation on the subflow to return
                an output parameter called "item". Accordingly the end state for the 
                inline flow has this output mapping returning a parameter called "item":
                <programlisting>
&lt;end-state id="finish"&gt;
    &lt;output-mapper&gt;
        &lt;mapping source="flowScope.item" target="item" /&gt;
    &lt;/output-mapper&gt;
&lt;/end-state&gt;
                </programlisting>
                With the above declarations we see how a subflow can pass output 
                parameters back to its parent flow. The remaining question is
                what sets "flowScope.item" which appears for the first time
                in the end state of the subflow?
            </para>
            <para>
                The answer lies in the "mapItemAction" bean invoked between the 
                view state and the end state in the subflow:
                <programlisting>
&lt;action-state id="mapItem"&gt;
    &lt;action bean="mapItemAction" /&gt;
    &lt;transition on="success" to="finish" /&gt;
&lt;/action-state&gt;
                </programlisting>
                The mapItemAction bean was defined in the itemlist-servlet.xml web context
                and is an istance of Web Flow's AttributeMapperAction. The purpose
                of AttributeMapperAction is to invoke an AttributeMapper and to perform
                mappings between two attribute sources. The AttributeMapper with which
                the mapItemAction bean is configured is an instance of DataMapper. It
                adds the following mapping:
                <programlisting>
addMapping(mapping.source("requestParameters.data").target("flowScope.item").value());
                </programlisting>
                With this declaration in place each time the AttributeMaperAction is 
                invoked it will create the flowScoped variable "item" based on the value
                of the "data" request parameter. Note that AttributeMapper is 
                Web Flow API for the &lt;attribute-mapper&gt; declarations used above
                to pass data from the inner subflow to the parent flow. 
            </para>
            <para>
                Once the inner subflow flow has completed the item is passed to the parent flow
                as an output parameter, which adds it to its flow-scoped list and transitions 
                to the initial "displayItemList" state.
            </para>
        </sect2>
    </sect1>
    <sect1 id="sellitem-sample">
        <title>Sellitem Example</title>
        <sect2>
            <title>Overview</title>
            <para>
                The Sellitem example demonstrates using Web Flow to build a 
                shopping cart wizard with
                a shipping rate subflow, decision states, service and data access 
                Spring POJO beans, Spring 2.0 form tags, and Web Flow's 
                FormAction bean for data binding, validation, and 
                error reporting.
            </para>
            <para>
                The Sellitem example breaks down its Spring application configuration
                into a number of files organized according to purpose. 
                Although the example itself uses a small number of beans you 
                may consider organizing a real-world application (with many more
                beans) according to similar principles. Before going into the specifics
                of each individual context use the diagram below to 
                get a brief overview of all configuration files including their
                location and purpose.
            </para>
            <mediaobject>
                <imageobject role="fo">
                    <imagedata fileref="images/sellitem-configuration.png" format="PNG" align="center"/>
                </imageobject>
                <imageobject role="html">
                    <imagedata fileref="images/sellitem-configuration.png" format="PNG" align="center"/>
                </imageobject>
                <caption>
                    <para>Sellitem Spring &amp; Web Flow Application Wiring</para>
                </caption>
            </mediaobject>
            
        </sect2>
        <sect2>
            <title>Web.xml</title>
            <para>
                The web.xml configuration maps "*.htm" requests to the sellitem servlet - 
                a Spring MVC DispatcherServlet:
                <programlisting>
&lt;servlet&gt;
    &lt;servlet-name&gt;sellitem&lt;/servlet-name&gt;
    &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;
    &lt;init-param&gt;
    &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
        &lt;param-value&gt;
            /WEB-INF/sellitem-servlet-config.xml
            /WEB-INF/sellitem-webflow-config.xml
        &lt;/param-value&gt;
    &lt;/init-param&gt;
&lt;/servlet&gt;

&lt;servlet-mapping&gt;
    &lt;servlet-name&gt;sellitem&lt;/servlet-name&gt;
    &lt;url-pattern&gt;*.htm&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
                </programlisting>
                The contextConifgLocation parameter for the DispatcherServlet indicates the 
                Spring MVC web context for the sellitem servlet is spread over two xml files: 
                sellitem-servlet-config.xml and sellitem-webflow-config.xml. 
                The web.xml also requests an additional Spring context to be loaded 
                from the classpath through the ContextLoaderListener:
                <programlisting>
&lt;context-param&gt;
    &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
    &lt;param-value&gt;
        classpath:org/springframework/webflow/samples/sellitem/services-config.xml
    &lt;/param-value&gt;
&lt;/context-param&gt;

&lt;listener&gt;
	&lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
&lt;/listener&gt;
                </programlisting>
                This service layer context defines beans to be referenced from 
                web flow definitions. The next section discusses the 
                content of this context in more detail.
            </para>
        </sect2>
        <sect2>
            <title>Services-config.xml</title>
            <para>
                The services-config.xml loaded from the classpath through Spring MVC's 
                ContextLoaderListener defines several beans for the service 
                and data access layers of the application. For example,
                the service context defines a DAO bean ("saleProcessor") and injects 
                it with a data source:
                <programlisting>
&lt;bean id="saleProcessor" class="org.springframework.webflow.samples.sellitem.JdbcSaleProcessor"&gt;
    &lt;property name="dataSource" ref="dataSource"/&gt;
&lt;/bean&gt;

&lt;bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"&gt;
    &lt;property name="driverClassName" value="org.hsqldb.jdbcDriver"/&gt;
    &lt;property name="url" value="jdbc:hsqldb:mem:sellItem"/&gt;
    &lt;property name="username" value="sa"/&gt;
&lt;/bean&gt;
                </programlisting>
                The services context also declares a bean of type InMemoryDatabaseCreator 
                set to autowire by type meaning that its fields will be compared against the types of
                beans available in the context and will be automatically set when a match is found. 
                Hence the dataSource bean is used to set the dataSource property 
                of InMemoryDatabaseCreator:
                <programlisting>
&lt;bean id="databaseCreator" class="org.springframework.webflow.samples.sellitem.InMemoryDatabaseCreator"
    autowire="byType"/&gt;
                </programlisting>
                Looking inside the InMemoryDatabaseCreator, its initDao() method invoked 
                during context initialization creates a table called T_SALES for use by the sample
                application. This table is created in an in-memory hsqldb database called
                sellitem (based on the url property of the dataSource bean).
                It's also worth noting the bean declarations related to declarative 
                transaction management:
                <programlisting>
&lt;tx:annotation-driven/&gt;

&lt;bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"&gt;
    &lt;property name="dataSource" ref="dataSource"/&gt;  
&lt;/bean&gt;
                </programlisting>
                The "&lt;tx:annotation-driven&gt;"declaration indicates transaction 
                configuration is governed by Java 5 annotations used in bean classes
                such as this annotation in the SaleProcessor interface:
                <programlisting>
@Transactional
public interface SaleProcessor {

    public void process(Sale sale);
}
                </programlisting>
                For annotated beans the Spring container automatically creates 
                proxies according to the transaction semantics in the annotation 
                metadata. The "&lt;tx:annotation-driven&gt;" tag has a transaction-manager 
                attribute but this attribute is not required if the transaction
                manager bean is named "transactionManager".
            </para>
        </sect2>
        <sect2>
            <title>Spring MVC Context</title>
            <para>
                The Spring MVC web context is split over two files - 
                sellitem-servlet-config.xml and sellitem-webflow-config.xml. 
                The sellitem-servlet-config.xml defines
                a controller and a view resolver. 
                <programlisting>
&lt;bean name="/pos.htm" class="org.springframework.webflow.executor.mvc.FlowController"&gt;
    &lt;property name="flowExecutor" ref="flowExecutor" /&gt;
&lt;/bean&gt;

&lt;!-- Maps flow view-state view names to JSP templates --&gt;
&lt;bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"&gt;
    &lt;property name="prefix" value="/WEB-INF/jsp/" /&gt;
    &lt;property name="suffix" value=".jsp" /&gt;
&lt;/bean&gt;
                </programlisting>
                FlowController is a web flow controller extending Spring MVC's AbstractController 
                delegating requests (in this case for the "/pos.htm" servlet path) to the 
                flowExecutor bean it is configured with. FlowController acts
                as gateway to Web Flow and a single controller instance can serve 
                the application as most of the actual control logic is encapsulated 
                in web flow definitions.
            </para>
            <para>
                The sellitem-webflow-config.xml defines web flow specific beans such as 
                a flow executor, a flow registry and a flow listener beans:
                <programlisting>
&lt;!-- Launches new flow executions and resumes existing executions --&gt;
&lt;flow:executor id="flowExecutor" registry-ref="flowRegistry"&gt;
    &lt;flow:execution-listeners&gt;
        &lt;flow:listener ref="listener" criteria="sellitem-flow" /&gt;
    &lt;/flow:execution-listeners&gt;
&lt;/flow:executor&gt;

&lt;!-- Creates the registry of flow definitions for this application --&gt;
&lt;flow:registry id="flowRegistry"&gt;
    &lt;flow:location path="/WEB-INF/flows/**/*-flow.xml" /&gt;
&lt;/flow:registry&gt;

&lt;!-- Observes the lifecycle of sellitem-flow executions --&gt;
&lt;bean id="listener"
    class="org.springframework.webflow.samples.sellitem.SellItemFlowExecutionListener" /&gt;
                </programlisting>
                The FlowExecutor is the central entry point into the 
                Spring Web Flow system. It drives the execution of flow definitions 
                configured through the flowRegistry. The flowRegistry bean is configured 
                to load definitions from files ending with "-flow.xml" in any
                subdirectory of /WEB-INF/flows. This matches to 
                sellitem-flow.xml, shipping-flow.xml, sellitem-simple-flow.xml,
                sellitem-conversation-scope-flow.xml and shipping-conversation-scope-flow.xml.
            </para>
            <para>
                As shown here the flow executor can also be configured with a flow 
                listener, which is a callback mechanism for flow execution lifecycle events. 
                The SellItemFlowExecutionListener extends FlowExecutionListenerAdapter - 
                a default implementation of the FlowExecutionListener interface
                sparing the need to implement methods for all lifecycle events.
            </para>
            <para>
                Looking inside SellItemFlowExecutionListener it implements the stateEntering
                method executed whenever a new state is about to be entered. 
                The logic in this method checks if the current web flow state
                has an attribute named "role" and if so it ensures the user 
                has that role:
                <programlisting>
String role = nextState.getAttributes().getString("role");
if (StringUtils.hasText(role)) {
    HttpServletRequest request = ((ServletExternalContext)context.getExternalContext()).getRequest();
    if (!request.isUserInRole(role)) {
        throw new EnterStateVetoException(context.getActiveFlow().getId(), context.getCurrentState().getId(),
                nextState.getId(), "State requires role '" + role
                        + "', but the authenticated user doesn't have it!");
    }
}
                </programlisting>
            </para>
            <para>
                Based on the above definitions - web.xml, Spring MVC controller bean, and
                web flow registry, the sellitem-flow can be initiated with the 
                following URI:
                <programlisting>
/swf-sellitem/pos.htm?_flowId=sellitem-flow                
                </programlisting> 
                <emphasis>
                Note: although it is possible to invoke the shipping-flow directly as well,
                it expects an input attribute and is intended to be invoked as a subflow.
                </emphasis>
            </para>
        </sect2>
        <sect2>
            <title>Sellitem-beans.xml</title>
            <para>
                Before tracing the sequence of states in sellitem-flow.xml notice the 
                import declaration at the bottom of that file:
                <programlisting>
&lt;import resource="sellitem-beans.xml"/&gt;
                </programlisting>
                The sellitem-beans.xml located in the same directory declares a 
                web flow FormAction bean for use in the flow definition and configures 
                it with a SaleValidator and a SellItemPropertyEditorRegistrar:
                <programlisting>
&lt;!-- Manages setting up, binding input to, and validating a Sale "backing wizard form object" --&gt;
&lt;bean id="formAction" class="org.springframework.webflow.action.FormAction"&gt;
    &lt;property name="formObjectClass" value="org.springframework.webflow.samples.sellitem.Sale"/&gt;
    &lt;property name="validator"&gt;
        &lt;bean class="org.springframework.webflow.samples.sellitem.SaleValidator"/&gt;
    &lt;/property&gt;
    &lt;!-- Installs property editors used to format non-String fields like 'shipDate' --&gt;
    &lt;property name="propertyEditorRegistrar"&gt;
        &lt;bean class="org.springframework.webflow.samples.sellitem.SellItemPropertyEditorRegistrar"/&gt;
    &lt;/property&gt;
&lt;/bean&gt;
                </programlisting> 
                The SellValidator will be used to validate form input data.
                The SellItemPropertyEditorRegistrar is responsible for registering 
                custom property editors. Such editors are used to bind text data from 
                HTML form fields to server-side Objects. For example 
                SellItemPropertyEditorRegistrar registers a custom date
                editor:
                <programlisting>
public void registerCustomEditors(PropertyEditorRegistry registry) {
    registry.registerCustomEditor(Date.class,
        new CustomDateEditor(new SimpleDateFormat("MM/dd/yyyy"), true));
}
                </programlisting>
                This editor will bind the shipDate form field in shippingDetailsForm.jsp
                to the shipDate property of the Sale object on the server side.
            </para>
        </sect2>
        <sect2>
            <title>Sellitem-flow Flow Definition</title>
            <para>
                The sellitem-flow uses a start action to invoke the setupForm method of the 
                formAction bean:
                <programlisting>
&lt;start-actions&gt;
    &lt;!-- create the backing form object and initialize a empty errors collection --&gt;
    &lt;action bean="formAction" method="setupForm"/&gt;
&lt;/start-actions&gt;                
                </programlisting>                
                A start action is invoked before entering the start state. 
                The setupForm method prepares a form object 
                and registers custom property editors.
                The form backing object class (as declared in sellitem-beans.xml)
                is of type Sale and is saved in flow scope under 
                the name of "sale" - it is possible to 
                override both the scope and the name of the form object in the 
                FormAction bean's declaration.
            </para>
            <para>
                The start state enterPriceAndItemCount is a view state, which resolves
                to the JSP page /WEB-INF/jsp/priceAndItemCountForm.jsp:
                <programlisting>
&lt;view-state id="enterPriceAndItemCount" view="priceAndItemCountForm"&gt;
    &lt;transition on="submit" to="enterCategory"&gt;
        &lt;action bean="formAction" method="bindAndValidate"&gt;
            &lt;attribute name="validatorMethod" value="validatePriceAndItemCount"/&gt;
        &lt;/action&gt;
    &lt;/transition&gt;
&lt;/view-state&gt;
                </programlisting>
                The priceAndItemCountForm.jsp page collects a price and an itemCount using
                Spring 2.0 form input tags binding form fields to properties in the form
                backing object "sale". When pressed, the submit button "_eventId_submit"
                causes a web flow transition for an event with the id of "submit" to
                the view state "enterCategory". Prior to transitioning the formAction's
                bindAndValidate method is called to perform binding and (partial) validation 
                using the validatePriceAndItemCount method of the validator object.
            </para>
            <para>
                The next view state enterCategory (based on categoryForm.jsp) 
                collects inputs for sale category and whether shipping is required. On 
                submit it transitions to the requiresShipping state:
                <programlisting>
&lt;view-state id="enterCategory" view="categoryForm"&gt;
    &lt;transition on="submit" to="requiresShipping"&gt;
        &lt;action bean="formAction" method="bind"/&gt;
    &lt;/transition&gt;
&lt;/view-state&gt;
                </programlisting>
                The requiresShipping state is a decision state making 
                flow routing decisions. It evaluates a boolean expression against the 
                executing flow and it decides where to transition to next. 
                Here the shipping boolean property of the "sale" form backing 
                object is checked to decide whether to go to the enterShippingDetails
                subflow state or proceed directly to processSale.
                <programlisting>
&lt;decision-state id="requiresShipping"&gt;
    &lt;if test="${flowScope.sale.shipping}" then="enterShippingDetails" else="processSale"/&gt;
&lt;/decision-state&gt;
                </programlisting>
                The enterShippingDetails subflow state is based on shipping-flow.xml 
                located in the same directory. The form backing object "sale" is
                passed to it as an input attribute using an attribute mapper declaration:
                <programlisting>
&lt;subflow-state id="enterShippingDetails" flow="shipping-flow"&gt;
    &lt;attribute-mapper&gt;
        &lt;input-mapper&gt;
            &lt;input-attribute name="sale"/&gt;
        &lt;/input-mapper&gt;
    &lt;/attribute-mapper&gt;
    &lt;transition on="finish" to="processSale"/&gt;
&lt;/subflow-state&gt;
                </programlisting>
                The shipping-flow subflow is a simple flow with one view state. It 
                collects the shipping details, binds the data and returns to its parent
                flow. The id of the subflow end state "finish" is returned to the 
                parent subflow state causing a transition to the processSale action state.
                <programlisting>
&lt;action-state id="processSale"&gt;
    &lt;bean-action bean="saleProcessor" method="process"&gt;
        &lt;method-arguments&gt;
            &lt;argument expression="flowScope.sale"/&gt;
        &lt;/method-arguments&gt;
    &lt;/bean-action&gt;
    &lt;transition on="success" to="finish"/&gt;
&lt;/action-state&gt;
                </programlisting>
                The saleProcessor bean, a POJO defined in services-config.xml
                is invoked using a "bean-action" declaration (as opposed to the "action" 
                declation used to invoke a web flow Action such as FormAction).
                The saleProcessor (an instance of JdbcSaleProcessor) performs a database
                update using the values of the Sale object and upon
                successful completion transitions to the end view state:
                <programlisting>
&lt;end-state id="finish" view="costOverview"&gt;
    &lt;entry-actions&gt;
        &lt;!-- force reinstall of property editors so costOverview can render formatted Sale values --&gt;
        &lt;action bean="formAction" method="setupForm"/&gt;
    &lt;/entry-actions&gt;
&lt;/end-state&gt;
                </programlisting>
                Then end state calls FormAction's setupForm method again.
                This does not re-create the "sale" form object (still in flow scope) 
                but it does ensure any custom property editors are 
                registered for use in rendering the JSP.
            </para>
        </sect2>
        <sect2>
            <title>Sellitem-simple-flow Flow Definition</title>
            <para>
            	A simpler version of the sellitem-flow is available in the sellitem-simple-flow.xml file.
            	This version uses a view state to gather shipping details instead of using a subflow. You
            	can launch the sellitem-simple-flow using the following URI:
                <programlisting>
/swf-sellitem/pos.htm?_flowId=sellitem-simple-flow
                </programlisting> 
            </para>
        </sect2>
        <sect2>
            <title>Sellitem-conversation-scope-flow Flow Definition</title>
            <para>
                This web flow is equivalent in functionality to the sellitem-flow definition
                described above. The main difference is that it uses "conversation" 
                scope to store the form backing object declared in 
                /WEB-INF/flows/converstation-scope/sellitem-beans.xml.
                <programlisting>
&lt;bean id="formAction" class="org.springframework.webflow.action.FormAction"&gt;
    &lt;property name="formObjectClass" value="org.springframework.webflow.samples.sellitem.Sale"/&gt;
    &lt;property name="formObjectScope" value="CONVERSATION"/&gt;
    &lt;property name="formErrorsScope" value="CONVERSATION"/&gt;
                </programlisting>
                Conversation scope retains attributes stored in it for the life
                of the flow execution and is shared by all flow sessions.
                For example when invoking the shipping details subflow the parent
                flow does not need to pass the "sale" form backing object because
                it is now stored in conversation scope and is accessible to both flows:
                <programlisting>
&lt;subflow-state id="enterShippingDetails" flow="shipping-conversation-scope-flow"&gt;
    &lt;transition on="finish" to="processSale"/&gt;
&lt;/subflow-state&gt;
                </programlisting>
                Also, when the "sale" object needs to be accessed it is done by referencing
                conversation cope:
                <programlisting>
&lt;decision-state id="requiresShipping"&gt;
    &lt;if test="${conversationScope.sale.shipping}" then="enterShippingDetails" else="processSale"/&gt;
&lt;/decision-state&gt;
                </programlisting>
				You can launch the sellitem-conversation-scope-flow using the following URI:
                <programlisting>
/swf-sellitem/pos.htm?_flowId=sellitem-conversation-scope-flow
                </programlisting>
        	</para>
        </sect2>
    </sect1>        
    <sect1 id="sellitem-JSF-sample">
        <title>Sellitem-JSF Example</title>
        <sect2>
            <title>Overview</title>
            <para>
                The Sellitem-JSF example uses Web Flow and JSF to build a shopping 
                cart wizard. Navigation logic and supporting "flow" scoped beans
                are supplied through Spring and Spring Web Flow while JSP's and 
                overall servlet processing is based on JSF technology.
            </para>
            <note>
                <para>
                    The underlying Web Flow definitions for the Sellitem and the Sellitem-JSF 
                    examples are very similar. To avoid repetition the documentation for 
                    the Sellitem-JSF example focuses primarily on the points of integration between 
                    Web Flow and JSF. For further general information on Web Flow definitions 
                    and supporting Java classes for the Sellitem example please refer to the 
                    <link linkend="sellitem-sample">Sellitem</link> example documentation.
                </para>
            </note>
        </sect2>
        <sect2>
            <title>Web.xml</title>
            <para>
                The web.xml contains standard JSF configuration including mappings for
                the JSF front servlet: it handles all requests ending with "*.jsf":
                <programlisting>
&lt;!-- Faces Servlet --&gt;
&lt;servlet&gt;
    &lt;servlet-name&gt;Faces Servlet&lt;/servlet-name&gt;
    &lt;servlet-class&gt;javax.faces.webapp.FacesServlet&lt;/servlet-class&gt;
    &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
&lt;/servlet&gt;

&lt;servlet-mapping&gt;
    &lt;servlet-name&gt;Faces Servlet&lt;/servlet-name&gt;
    &lt;url-pattern&gt;*.jsf&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
                </programlisting>
            </para>
            <para>
                In addition the web.xml loads to Spring contexts with the 
                ContextLoaderListener:
                <programlisting>
&lt;context-param&gt;
    &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
    &lt;param-value&gt;
        classpath:org/springframework/webflow/samples/sellitem/services-config.xml
        /WEB-INF/webflow-config.xml
    &lt;/param-value&gt;
&lt;/context-param&gt;

&lt;listener&gt;
    &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
&lt;/listener&gt;
                </programlisting>
                The services-config.xml contains POJO beans required for the services and 
                data access layers of the application. These declarations are very similar
                to the Sellitem example (and explained in more detail there). 
                The webflow-config.xml context contains Web Flow related bean 
                definitions. These definitions will be explained a little bit 
                further on in the context of how they fit into the JSF phases 
                lifecycle.
            </para>
        </sect2>
        <sect2>
            <title>JSF Plumbing (faces-config.xml)</title>
            <para>
                The Spring framework has several classes to help JSF applications
                to use Spring beans as JSF managed beans and to do dependency injection
                on a navigation handler or a phase listener using Spring.
                This is demonstrated in the faces-config.xml of Sellitem-JSF:
                <programlisting>
&lt;application&gt;
    &lt;!-- Navigation handler proxy for a Spring-managed bean that is the Web Flow Navigation Handler --&gt;
    &lt;navigation-handler&gt;
        org.springframework.web.jsf.DelegatingNavigationHandlerProxy
    &lt;/navigation-handler&gt;
    ...
    &lt;variable-resolver&gt;
        org.springframework.web.jsf.
    &lt;/variable-resolver&gt;
    &lt;!-- Extended "webApplicationContext" resolver --&gt;
    &lt;variable-resolver&gt;
        org.springframework.web.jsf.WebApplicationContextVariableResolver
    &lt;/variable-resolver&gt;
&lt;/application&gt;
&lt;lifecycle&gt;
    &lt;!-- Multi-caster that broadcast phase events to all PhaseListeners managed by Spring --&gt;
    &lt;phase-listener&gt;org.springframework.web.jsf.DelegatingPhaseListenerMulticaster&lt;/phase-listener&gt;
&lt;/lifecycle&gt;
                </programlisting>
                The DelegatingNavigationHandlerProxy delegates to a NavigationHandler 
                bean defined in the Spring root WebApplicationContext. For Sellitem-JSF
                this is the jsfNavigiationHandler bean in /WEB-INF/webflow-config.xml:
                <programlisting>
&lt;bean id="jsfNavigationHandler" class="org.springframework.webflow.executor.jsf.FlowNavigationHandler" /&gt;
                </programlisting>
            </para>
            <note>
                <para>
	                Web Flow's FlowNavigationHandler could have been installed directly
	                in faces-config.xml - adding it through a delegating proxy is done for 
	                demonstration purposes and useful for further Spring container services.
                </para>
            </note>
            <para>
                The FlowNavigationHandler provides a point of integration between Web Flow and 
                JSF. It can delegate JSF requests to the Web Flow system (such as when 
                a flow is initiated or is ongoing) or return control to a 
                standard JSF navigation handler implementation (when 
                a web flow is not ongoing). As will
                be shown further down a web flow initiation or a continuation 
                is detected through the 
                presence of a _flowId or a _flowExecutionKey parameter.
            </para>
            <para>
                The DelegatingVariableResolver and the WebApplicationContextVariableResolver
                are Spring provided JSF VariableResolvers. The DelegatingVariableResolver
                allows Spring beans to be used as JSF variables (such as in managed bean 
                declarations). The WebApplicationContextVariableResolver exposes the 
                Spring WebApplicationContext instance as a JSF variable named 
                "webApplicationContext". This allows access to the Spring web context
                for obtaining any Spring managed beans and resources.
            </para>
            <para>
                The DelegatingPhaseListenerMulticaster is another Spring provided class,
                which delegates beforePhase and afterPhase JSF events to Spring-managed
                PhaseListener beans present in the Spring root WebApplicationContext.
                In the case of Sellitem-JSF there is one PhaseListener bean definition
                in its web context /WEB-INF/webflow-config.xml:
                <programlisting>
&lt;bean id="flowPhaseListener" class="org.springframework.webflow.executor.jsf.FlowPhaseListener" /&gt;
                </programlisting>
            </para>
            <note>
                <para>
	                The Web Flow's FlowPhaseListener could have been installed directly
	                in faces-config.xml - adding it through a delegating proxy is done for 
	                demonstration purposes and useful for further Spring container services.
                </para>
            </note>
            <para>
                The FlowPhaseListener invoked during beforePhase and afterPhase JSF events
                is responsible for managing an active FlowExecution and making it available
                to other JSF artifacts during the lifecycle of a JSF request. 
            </para>
            <para>
                The faces-config for Sellitem-JSF has two more definitions based on 
                Web Flow provided classes:
                <programlisting>
&lt;property-resolver&gt;
    org.springframework.webflow.executor.jsf.FlowPropertyResolver
&lt;/property-resolver&gt;
&lt;variable-resolver&gt;
    org.springframework.webflow.executor.jsf.FlowVariableResolver
&lt;/variable-resolver&gt;
                </programlisting>
                The FlowVariableResolver makes it possible to use the "flowScope" 
                variable in JSF expressions. The "flow" scope is a unique feature of 
                Web Flow allowing state to be retained for the duration of a flow -
                less than session scope but typically longer than a single request.
                The FlowPropertyResolver allows resolution of property paths from a 
                FlowExecution context.
            </para>
        </sect2>
        <sect2>
            <title>Web Flow Definitions</title>
            <para>
                Examining the definitions in faces-config.xml highlighted the ability
                to use Spring beans as JSF managed beans as well as plug Web Flow
                definitions for JSF navigation logic. Now we can turn to the question
                of how to configure specific web flow definitions.
            </para>
            <para>
                The Spring web context /WEB-INF/webflow-config.xml contains the following
                flow registry bean definition:
                <programlisting>
&lt;!-- Creates the registry of flow definitions for this application --&gt;
&lt;flow:registry id="flowDefinitionLocator"&gt;
    &lt;flow:location path="/WEB-INF/flows/sellitem-flow.xml" /&gt;
&lt;/flow:registry&gt;
                </programlisting>
                Here the flow registry definies the path to one web flow definition - 
                sellitem-flow.xml. The flow registry bean with an id of "flowDefinitionLocator"
                is accessed by the FlowPhaseListener, which makes the specified web flow
                definitions available for use in JSF. The intro.jsp page shows how the 
                configured web flow sellitem-flow.xml can be invoked:
                <programlisting>
&lt;h:form&gt;
    &lt;h:commandLink value="Sell Item" action="flowId:sellitem-flow"/&gt;
&lt;/h:form&gt;
                </programlisting>
                This causes the sellitem-flow to be initiated. Once a flow is initiated
                each next JSP page advancing through the view states of the Sellitem flow
                definition passes a parameter called _flowExecutionKey 
                allowing the flow to be continued by the FlowPhaseListener:
                <programlisting>
&lt;input type="hidden" name="_flowExecutionKey" value="${flowExecutionKey}"/&gt;
                </programlisting>
            </para>
            <para>
                A few notable differences between Sellitem and  Sellite-JSF to keep in mind:
                <orderedlist>
                    <listitem>
                        In its web flow definition Sellitem-JSF uses actual 
                        JSP names (instead of the logical view names used
                        in Sellitem) to be rendered by JSF.
                    </listitem>
                    <listitem>
                        The JSP pages in Sellitem-JSF use unified EL to 
                        access the flowScoped Sale object - e.g. #{flowScope.sale.price}.
                    </listitem>
                    <listitem>
                        Sellitem-JSF uses JSF tags for UI and Sellitem uses Spring form tags.
                    </listitem>
                </orderedlist>
                For more information and understanding on how the Sellitem flow
                definition is navigated please refer to the documentation for the 
                <link linkend="sellitem-sample">Sellitem</link> example.            
            </para>
        </sect2>
    </sect1>
    <sect1 id="phonebook-Portlet-sample">
        <title>Phonebook-Portlet Example</title>
        <sect2>
            <title>Overview</title>
            <para>
                The Phonebook-Portlet demonstrates how to run the 
                <ulink url="http://www.ervacon.com/products/swf/intro/index.html">Phonebook</ulink>
                sample as a JSR-168 portlet. The functionality for Phonebook and Phonebook-Portlet
                including web flow definitions, JSP pages, and Java classes is the same and 
                already well documented.
                The focus in Phonebook-Portlet is specifically on how to configure
                and run Phonebook in a Portal container.
            </para>
            <note>
                <para>
                    JSR-168 defines portlets but not how portlets integrate into a 
                    portal container. This process is left open to portal vendors who 
                    have their own individual mechanisms.
                    The Phonebook-Portlet sample is configured to run with
                    <ulink url="http://portals.apache.org/pluto/">Apache Pluto</ulink> - 
                    a reference implementation of the Java Portlet Specification. 
                    However, its dependence on Pluto is limited to configuration in web.xml. 
                    Hence it should be easy to adapt for use
                    in other Portal/Portlet implementations after learning the 
                    deployment steps specific for that implementation.
                </para>
            </note>            
        </sect2>
        <sect2>
            <title>Portal/Portlet Related Software Used in the Sample</title>
            <para>
                This section provides a very brief introduction to the portal related 
                supporting software used in the sample - namely Apache Pluto 
                and the Portlet MVC framework. If this is not new for you
                feel free to skip to the next section.
            </para>
            <sect3>
                <title>Apache Pluto</title>
                <para>
                    For those familiar with servlet applications the process
                    of deploying and running a portlet application can be 
                    confusing and requires some explanation.
                    Typically an application with JSR-168 portlets runs in 
                    one webapp while a portal/portlet container runs
                    in a separate webapp making cross-context calls to 
                    portlets. How exactly this is configured 
                    depends on each portal vendor.
                </para>
                <para>
                    Pluto is an open-source reference implementation of the 
                    Java Portlet specification. The following general steps 
                    are required to run portlets with it. First the 
                    the portlet application's web.xml is "injected" with 
                    configuration required for Pluto. Secondly Pluto's 
                    Portal web application, usually set to run at
                    http://localhost:8080/pluto/portal
                    is used to add or remove portlets to one or more 
                    portal container pages. 
                </para>
                <para>
                    The web.xml for the Phonebook-Portlet sample has 
                    already been "injected" with the configuration required 
                    for Pluto 1.1.0. Although this enables it for use with Pluto 
                    you must still use the
                    admin pages of Pluto's Portal web application to add
                    the Phonebook-Portlet to a test portal page. For more
                    information on how to do this please follow instructions from
                    Apache Pluto.
                </para>
            </sect3>
            <sect3>
                <title>Portlet MVC Framework</title>
                <para>
                    The Portlet MVC framework represents Spring's support for JSR-168.
                    It has many parallels with the Spring MVC framework such 
                    as the DispatcherPortlet, the Controller interface, 
                    handler mappings, view resolvers, and exception handlers.
                    The main differences between Portlet MVC and Spring MVC 
                    have to do with the lifecycles of a portlet and its 
                    distinct phases as defined in the Porlet Specification: 
                    the action and the render phases. 
                    For more information see
                    <ulink url="http://static.springframework.org/spring/docs/2.0.x/reference/portlet.html">
                    Chapter 16 (Portlet MVC Framework)</ulink> from the Spring reference
                    documentation.
                </para>
            </sect3>
        </sect2>
        <sect2>
            <title>Portlet.xml Configuration</title>
            <para>
                Portlet.xml is a standard deployment descriptor where 
                portlet resources are defined. The Phonebook-Portlet
                is based the Portlet MVC DispatcherPorlet:
                <programlisting>
&lt;portlet-class&gt;
    org.springframework.web.portlet.DispatcherPortlet
&lt;/portlet-class&gt;
                </programlisting>
                The DispatcherPortlet is Spring's implementation of the Portlet interface
                dispatching requests for a portlet to registered Portlet MVC handlers.
                The phonebook portlet is configured with the following Spring 
                contexts containing Portlet MVC handler, controller and 
                view resolver beans:
                <programlisting>
&lt;init-param&gt;
    &lt;name&gt;contextConfigLocation&lt;/name&gt;
    &lt;value&gt;
        /WEB-INF/phonebook-portlet-config.xml /WEB-INF/phonebook-webflow-config.xml
    &lt;/value&gt;
&lt;/init-param&gt;
                </programlisting>
                The above configuration defines phonebook as a portlet resource. In order
                to use it in a portal/portlet container 
                additional web.xml configuration is required.
            </para>
        </sect2>
        <sect2>
            <title>Web.xml Configuration</title>
            <para>
                The Java Portlet Specification is defined as a layer over existing Servlet 
                infrastructure. Therefore some sort of a servlet is required to accept servlet
                requests and expose portlet resources. Portal vendors 
                provide such servlets and specific configuration varies by vendor. 
                The Phonebook-Portlet has the following Apache Pluto servlet definition
                and servlet mapping:
                <programlisting>
&lt;!-- Generated Portlet Wrapper Servlet for Apache Pluto deployment --&gt;
&lt;servlet&gt;
    &lt;servlet-name&gt;phonebook&lt;/servlet-name&gt;
    &lt;servlet-class&gt;org.apache.pluto.core.PortletServlet&lt;/servlet-class&gt;
    &lt;init-param&gt;
        &lt;param-name&gt;portlet-name&lt;/param-name&gt;
        &lt;param-value&gt;phonebook&lt;/param-value&gt;
    &lt;/init-param&gt;
    &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
&lt;/servlet&gt;
&lt;servlet-mapping&gt;
    &lt;servlet-name&gt;phonebook&lt;/servlet-name&gt;
    &lt;url-pattern&gt;/PlutoInvoker/phonebook&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
                </programlisting>
            </para>
            <note>
                <para>
                    The above configuration was auto generated using ant tasks from 
                    Apache Pluto 1.1.0. This configuration is included in web.xml 
                    for convenience and also as an example.
                    For the most up-to-date information on required configuration please
                    check Pluto's documentation.
                </para>
            </note>
            <para>
                The web.xml configuration also contains the following servlet definition:
                <programlisting>
&lt;servlet&gt;
    &lt;servlet-name&gt;viewRendererServlet&lt;/servlet-name&gt;
    &lt;servlet-class&gt;
        org.springframework.web.servlet.ViewRendererServlet
    &lt;/servlet-class&gt;
&lt;/servlet&gt;
&lt;servlet-mapping&gt;
    &lt;servlet-name&gt;viewRendererServlet&lt;/servlet-name&gt;
    &lt;url-pattern&gt;/WEB-INF/servlet/view&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
                </programlisting>
            </para>
            <para>
                The main purpose of this servlet is to allow reuse of Spring MVC's flexible
                view resolution and rendering capabilities in a Portlet application. 
                The DispatcherPortlet converts a PortletRequest/PortletResponse to an
                HttpServletRequest/HttpServletResponse and then performs an include of 
                this servlet.
            </para>
        </sect2>        
        <sect2>
            <title>Portlet MVC Configuration</title>
            <para>
                The phonebook-portlet-config.xml is very similar to the Spring MVC 
                equivalent phonebook-servlet.xml from the Phonebook sample. The main
                difference is in the use of a PortletModeHandlerMapping:
                <programlisting>
&lt;bean id="portletModeControllerMapping"
	class="org.springframework.web.portlet.handler.PortletModeHandlerMapping"&gt;
    &lt;property name="portletModeMap"&gt;
        &lt;map&gt;
            &lt;entry key="view" value-ref="flowController"/&gt;
        &lt;/map&gt;
    &lt;/property&gt;
&lt;/bean&gt;
                </programlisting>
                and a PortletFlowController:
                <programlisting>
&lt;bean id="flowController" class="org.springframework.webflow.executor.mvc.PortletFlowController"&gt;
    &lt;property name="flowExecutor" ref="flowExecutor"/&gt;
    &lt;property name="defaultFlowId" value="search-flow"/&gt;
&lt;/bean&gt;
                </programlisting>
                A PortletModeHandlerMapping allows mapping specific to each 
                portlet mode. The VIEW mode in this case is mapped to the 
                flowController bean, which delegates the request to Web Flow's 
                executor for launching or resuming a flow from a flow definition.
                For more information on Phonebook flow definitions please
                refer to the 
                <ulink url="http://www.ervacon.com/products/swf/intro/index.html">Phonebook</ulink> 
                sample documentation.
            </para>
            <para>
                One last thing to observe is the following configuration in
                /WEB-INF/phonebook-webflow-config.xml:
                <programlisting>
&lt;!-- Launches new flow executions and resumes existing executions. --&gt;  
&lt;flow:executor id="flowExecutor" registry-ref="flowRegistry"&gt;
    &lt;flow:execution-attributes&gt;
        &lt;!-- execution redirects don't apply in a Portlet environment --&gt;
        &lt;flow:alwaysRedirectOnPause value="false"/&gt;
    &lt;/flow:execution-attributes&gt;
&lt;/flow:executor&gt;
                </programlisting>
                As the comment indicates the default behavior of redirect after submit
                must be turned off in a portlet environment where there is no HTTP redirect.
                For more information on the alwaysRedirectOnPause refer to the following
                <ulink url="http://www.ervacon.com/products/swf/tips/tip4.html">article</ulink>.
            </para>
        </sect2>
    </sect1>    
</chapter>
