38
Reference Documentation Version 1.0 RC1 (Work in progress) Copyright (c) 2004-2005 Keith Donald, Erwin Vervaet, Alef Arendsen Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee for such copies and further provided that each copy contains this Copyright Notice, whether distributed in print or electronically.

Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

Reference Documentation

Version 1.0 RC1

(Work in progress)

Copyright (c) 2004-2005 Keith Donald, Erwin Vervaet, Alef Arendsen

Copies of this document may be made for your own use and for distribution to others, provided that you do notcharge any fee for such copies and further provided that each copy contains this Copyright Notice, whether

distributed in print or electronically.

Page 2: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

Table of ContentsPreface ................................................................................................................................................1. Introduction ..................................................................................................................................

1.1. Overview ............................................................................................................................. 11.2. Packaging overview ............................................................................................................. 11.3. High level architecture .......................................................................................................... 11.4. Package structure ................................................................................................................. 1

1.4.1. org.springframework.webflow .................................................................................... 21.4.2. org.springframework.webflow.action .......................................................................... 21.4.3. org.springframework.webflow.builder ........................................................................ 21.4.4. org.springframework.webflow.execution ..................................................................... 21.4.5. org.springframework.webflow.executor ...................................................................... 21.4.6. org.springframework.webflow.registry ........................................................................ 21.4.7. org.springframework.webflow.support ........................................................................ 31.4.8. org.springframework.webflow.test .............................................................................. 3

1.5. Support ................................................................................................................................ 32. Flow definition ..............................................................................................................................

2.1. Introduction ......................................................................................................................... 42.2. Flow .................................................................................................................................... 4

2.2.1. XML-based flow template .......................................................................................... 52.2.2. Java flow API example .............................................................................................. 5

2.3. State .................................................................................................................................... 52.4. Transitionable State .............................................................................................................. 6

2.4.1. XML-based state template .......................................................................................... 62.4.2. Java state API example .............................................................................................. 7

2.5. Transition ............................................................................................................................ 72.5.1. Transition XML template ........................................................................................... 82.5.2. Transition Java API example ...................................................................................... 82.5.3. Action transition criteria ............................................................................................ 82.5.4. Global transitions ...................................................................................................... 8

2.6. Concrete state types .............................................................................................................. 92.6.1. ViewState ................................................................................................................. 102.6.2. ActionState ............................................................................................................... 142.6.3. DecisionState ............................................................................................................ 202.6.4. SubflowState ............................................................................................................. 222.6.5. EndState ................................................................................................................... 24

3. Flow execution ..............................................................................................................................3.1. Introduction ......................................................................................................................... 273.2. FlowExecution ..................................................................................................................... 27

4. Phonebook - a typical Spring Web Flow application .....................................................................4.1. Introduction ......................................................................................................................... 284.2. Designing the flow ............................................................................................................... 28

4.2.1. A small narrative ....................................................................................................... 284.2.2. Graphical representation of our flow ........................................................................... 294.2.3. Web flow: a state machine ......................................................................................... 30

4.3. Configuring the flow implementation using Java or XML ....................................................... 314.3.1. Configuring the flow in XML ..................................................................................... 31

Spring Web Flow Version 1.0 RC1 ii

Page 3: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

PrefaceMany web applications consist of a mix of free browsing, where the user is allowed to navigate a web site asthey please, and controlled navigations where the user is guided through a series of steps towards completion ofa business goal.

Consider the typical shopping cart application. While a user is shopping, she is freely browsing availableproducts, adding her favorites to her cart while skipping over others. This is a good "free browsing" use case.However, when the user decides to checkout, a controlled workflow begins--the checkout process. Such aprocess represents a single user conversation that takes place over a series of steps, and navigation fromstep-to-step is controlled. The entire process represents an discrete application transaction that must completeexactly once or not at all.

Consider some other good examples of "controlled navigations": applying for a loan, paying your taxes on-line,booking a trip reservation, registering an account, or updating a warehouse inventory.

Traditional approaches to modeling and enforcing such controlled navigations or "flows" fall flat, and fail toexpress the Flow as a first class concept. Spring Web Flow (SWF) is a component of the Spring Framework'sweb stack focused on solving this problem in a productive and powerful manner.

Spring Web Flow Version 1.0 RC1 iii

Page 4: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate
Page 5: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

Chapter 1. Introduction

1.1. Overview

Spring Web Flow (SWF) is a component of the Spring Framework's web stack focused on the definition andexecution of page flow within a web application.

The system allows you to capture a logical flow of your web application as a self-contained module that can bereused in different situations. Such a flow guides a single user through the implementation of a businessprocess, and represents a single user conversation. Flows often execute across HTTP requests, have state,exhibit transactional characteristics, and may be dynamic and/or long-running in nature.

Spring Web Flow exists at a higher level of abstraction, integrating as a self-contained page flow engine withinbase frameworks such as Struts, Spring MVC, Portlet MVC, and JSF. SWF provides you the capability tocapture your application's page flow explicity in a declarative, highly-portable, and highly-manageable fashion.SWF is a powerful controller framework based on a finite-state machine, fully addressing the "C" in MVC.

1.2. Packaging overview

Spring Web Flow has been architected as a self-contained page flow engine with few required dependencies onthird-party APIs. All dependencies are carefully managed.

At a minimum, to use Spring Web Flow you need:

• spring-webflow (the framework)• spring-core (miscellaneous utility classes used internally by the framework)• spring-binding (the Spring data binding framework, used internally)• commons-logging (a simple logging facade, used internally)

Most users will embed SWF as a component within a larger web application development framework, as SWFis a focused controller technology that expects a calling system to care for request mapping and responserendering. In this case, those users will depend on a thin integration piece for their environment. For example,those executing flows within a Servlet might use the Spring MVC integration to care for dispatching requests toSWF and rendering responses for SWF view selections.

It is important to note that Spring Web Flow, like Spring, is a layered framework, packaged in a manner thatallows teams to use the parts they need and nothing else. For example, one team might use Spring Web Flow ina Servlet environment with Spring MVC, and thus require the Spring MVC integration. Another team mightuse SWF in a Portlet environment, and thus require the Portlet MVC integration. Another team might mix andmatch. A major benefit of SWF is that it allows you to define reusable, self-contained controller modules thatcan execute in any environment.

1.3. High level architecture

TODO Give high level overview of internal SWF architecture and layering (mentioned above). Provide visual.

1.4. Package structure

Spring Web Flow Version 1.0 RC1 1

Page 6: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

This section provides an overview of the logical package structure of the SWF codebase. The dependencies foreach package are clearly noted.

1.4.1. org.springframework.webflow

The webflow package contains the central foundational abstractions of the framework. These abstractionsconsist of definition artifacts such as Flow, State, and Action that define the core "domain language" forexpressing flows.

• Dependencies: spring-core, spring-binding, commons-logging

1.4.2. org.springframework.webflow.action

The action package contains implementations of the core "Action" abstraction for executing arbitrary commandlogic within a Flow.

• Dependencies: webflow, spring-beans (optional), spring-context (optional)

1.4.3. org.springframework.webflow.builder

The builder package contains abstractions used at configuration-time for building and assembling Flows, inJava or from externalized resources such as XML files.

• Dependencies: webflow, webflow.support

1.4.4. org.springframework.webflow.execution

The execution package contains runtime abstractions for executing Flows and managing flow executions. Thisis where the implementation of the Spring Web Flow's finite-state machine resides. This is also where therepository subsystem resides, for storing active flow executions beyond a single request into the server. Thissubsystem forms the basis for Spring Web Flow's continuation server.

• Dependencies: webflow, webflow.util, commons-codec (optional)

1.4.5. org.springframework.webflow.executor

The executor package is the highest-level package in the framework. It contains implementations of "flowexecutors" that drive the execution of flows. This is where the facade for external systems that call into theSpring Web Flow system resides. This is also where integration layers for Spring MVC (Servlet and Portlet),Struts, and Java Server Faces (JSF) reside.

• Dependencies: webflow.execution, spring-webmvc (optional), spring-portlet (optional), Struts (optional),Java Server Faces (optional).

1.4.6. org.springframework.webflow.registry

The registry package contains the subsystem for managing registries of flow definitions that are eligible forexecution.

• Dependencies: webflow, webflow.builder, webflow.execution, spring-beans (optional)

Introduction

Spring Web Flow Version 1.0 RC1 2

Page 7: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

1.4.7. org.springframework.webflow.support

The support package contains general-purpose implementations of the core definitional artifacts. Theseimplementations are mainly used internally by the other packages of the framework but are also usable directlyby developers.

• Dependencies: webflow

1.4.8. org.springframework.webflow.test

The test package contains support for testing Flow Executions out-of-container, as well as unit testing artifactssuch as Actions in isolation.

• Dependencies: webflow, webflow.execution, junit, spring-mock

A package dependency noted as (optional) means that the dependency is needed to compile the package but isoptionally needed at runtime (depending on your use of the package). For example, use of Spring Web Flow ina Servlet environment entails use of the context.servlet package and requires the Servlet API to be in theclasspath, but not the Portlet API.

For the exact list of dependencies, as well as supported product usage configurations, see the SWF ivydependency manager descriptor located within the SWF distribution at spring-webflow/ivy.xml

1.5. Support

Spring Web Flow 1.0 is supported on Spring 1.2.7 or later.

The community support forum is located at http://forum.springframework.org.

Introduction

Spring Web Flow Version 1.0 RC1 3

Page 8: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

Chapter 2. Flow definition

2.1. Introduction

Spring Web Flow allows developers to build reusable, self-contained controller modules called flows. A flow isa blueprint for a user conversation (or dialog) that drives the execution of application code to complete abusiness goal.

Flows are defined declaratively using a rich domain-specific language (DSL) tailored to the problem domain ofpage flow. Currently, Java-based and XML-based forms of this language are provided.

This chapter documents Spring Web Flow's core flow definition language. You'll learn the core domainconstructs of the system and how those constructs are representable in an externalized XML form.

2.2. Flow

A flow is defined by a single instance of org.springframework.webflow.Flow. This is the central domainartifact representing the definition of a conversation.

A flow consists of a set of one or more states, where each state defines a step in the flow that, when entered,executes a behavior. What behavior is executed is a function of the state's type and configuration. The outcomeof a state's execution, called an event, is used by the flow to drive a state transition.

Exactly one of a flow's states is the startState that defines the starting point of the flow. Optionally, a flowcan have one or more end states defining the ending points of the flow.

The properties of a org.springframework.webflow.Flow are summarized below:

Table 2.1. Flow properties

Property name Description Cardinality Default value

id The identifier of the flow, typically uniqueto all other flows of the application.

1

properties Additional custom properties about theflow.

0..* None

states The steps of the flow. 1..*

startState The starting point of the flow. 1

startActions The list of actions to execute each time anexecution of the flow is started.

0..* Empty

globalTransitions The set of transitions shared by all statesof this flow.

0..* Empty

endActions The list of actions to execute each time anexecution of the flow ends.

0..* Empty

exceptionHandlers An ordered set of handlers to be appliedwhen an exception is thrown within a state

0..* Empty

Spring Web Flow Version 1.0 RC1 4

Page 9: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

Property name Description Cardinality Default value

of the flow.

inlineFlows A set of inner flows that will be called assubflows; these flows are locally scoped tothe outer flow.

0..* Empty

Below is a high level example of how these Flow properties can be configured in XML form or directly in Javacode.

2.2.1. XML-based flow template

<flow start-state="startingPoint"><property .../>

<start-actions>...

</start-actions>

<-- your state definitions go here -->

<global-transitions>...

</global-transitions>

<end-actions>...

</end-actions>

<exception-handler .../>

<inline-flow>...

</inline-flow></flow>

2.2.2. Java flow API example

Flow flow = new Flow("id");flow.setProperty(..., ...);flow.addState(...);flow.setStartState("startingPoint");flow.addStartAction(...);flow.addGlobalTransition(...);flow.addEndAction(...);flow.addExceptionHandler(...);flow.addInlineFlow(...);

2.3. State

A state defines the behavior for a step of a flow. The base class for all Flow state types isorg.springframework.webflow.State. This abstract class defines common properties applicable to all statetypes, which include:

Table 2.2. State properties

Flow definition

Spring Web Flow Version 1.0 RC1 5

Page 10: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

Property name Description Cardinality Default value

id The id of the state, unique to its containingFlow.

1

flow The owning Flow. 1

properties Additional custom properties about thestate.

0..* None

entryActions The list of actions to execute each time thestate is entered.

0..* Empty

exceptionHandlers An ordered set of handlers to be appliedwhen an exception is thrown within thestate.

0..* Empty

2.4. Transitionable State

A central subclass of State is org.springframework.webflow.TransitionableState. This abstract classdefines common properties applicable to all state types that execute transitions to other states in response toevents. These properties include:

Table 2.3. TransitionableState properties

Property name Description Cardinality Default value

transitions The eligible paths out of this state. 1..*

exitActions The list of actions to execute each timethis state is exited.

0..* Empty

Below is a high-level example of how these common TransitionableState properties can be configured in XMLform or directly in Java code.

2.4.1. XML-based state template

<flow start-state="stateId"><some-state id="stateId">

<property .../>

<entry-actions>...

</entry-actions>

<transition .../>

<exit-actions>...

</exit-actions>

<exception-handler ../></some-state>

</flow>

Flow definition

Spring Web Flow Version 1.0 RC1 6

Page 11: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

2.4.2. Java state API example

Flow flow = new Flow("id");TransitionableState state = new SomeConcreteStateType(flow, "stateId");state.setProperty(..., ...);state.addEntryAction(...);state.addTransition(...);state.addExitAction(...);

2.5. Transition

A transition takes a flow from one state to another, defining a path through the flow.

Recall that all TransitionableStates have a set of one or more transitions, each defining a path to another state inthe flow (or a recursive path back to the same state). When a transitionable state is entered, it executes abehavior. For example, a transitionable state called "Display Form" may display a form to the user. Theoutcome of the state's execution, called an event, is used to drive execution of one of the state's transitions. Forexample, the user may press the form submit button which signals a submit event that matches the transition tothe "Process Submit" state.

This event-driven transition execution process is shown graphically below:

Transition execution

A transition is defined by an instance of org.springframework.webflow.Transition. Its properties aresummarized below:

Table 2.4. Transition properties

Property name Description Cardinality Default value

properties Additional properties describing thetransition.

0..* None

matchingCriteria The strategy that determines if thetransition matches on the occurence anevent.

1 Always matches

executionCriteria The strategy that determines if thetransition, once matched, is allowed to

1 Always allowed

Flow definition

Spring Web Flow Version 1.0 RC1 7

Page 12: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

Property name Description Cardinality Default value

execute.

targetStateResolver The strategy that calculates the target stateof the transition.

1

Below is a high-level example of how a Transition can be configured in XML form or directly in Java code.

2.5.1. Transition XML template

<transition on="event" to="targetState"><property .../><action ../>

</transition>

2.5.2. Transition Java API example

Transition transition = new Transition(new StaticTargetStateResolver("targetState"));transition.setProperty(..., ...);transition.setMatchingCriteria(new EventIdTransitionCriteria("event"));transition.setExecutionCriteria(...);

2.5.3. Action transition criteria

In the XML example note the support for the action element within the transition element.

A transition may be configured with one or more actions that execute before the transition itself executes, aspart of the executionCriteria. If one or more of these actions do not complete successfully the transition willnot be allowed. This action transition criteria makes it possible to execute arbitrary logic after a transition ismatched but before it is executed. This is useful when you want to execute event post-processing logic. A goodexample is executing data binding and validation behavior after a form submit event.

2.5.4. Global transitions

As outlined, one or more transitions are added to all TransitionableState types, attached at the state-level.Optionally, transitions may also be added at the flow-level where they are shared by all states. These sharedtransitions are called global transitions.

When an event is signaled in a transitionable state the state will first try and match one of its own transitions. Ifthere is no match at the state level the set of global transitions will be tested. If there still no match aNoMatchingTransitionException will be thrown.

Global transitions are useful in situations where many states of the flow share the same transitional criteria. Forexample, consider a navigation menu that displays alongside each view of a flow. Logic to process navigationmenu events is needed by all view states. This is the problem global transitions are designed to solve.

2.5.4.1. Global transitions - XML example

Flow definition

Spring Web Flow Version 1.0 RC1 8

Page 13: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

The following example shows transitions defined at the state level, as well as global transitions inherited fromthe flow level.

<flow start-state="state1">

<some-state id="state1"><transition on="localEvent1" to="state2"/>

</some-state>

<some-state id="state2"><transition on="localEvent1" to="state1"/>

</some-state>

<global-transitions><transition on="globalEvent1" to="state1"/><transition on="globalEvent2" to="state2"/>

</global-transitions>

</flow>

In this example state1 defines one transition and also inherits the two others defined within theglobal-transitions element. Any other states defined within this flow would also inherit those globaltransitions.

This example is shown graphically below:

Global transitions

2.6. Concrete state types

Spring Web Flow has five (5) built-in concrete state types, all contained within theorg.springframework.webflow package. These states execute common controller behaviors including:

1. allowing the user to participate in a flow (ViewState)

2. executing business application code (ActionState)

3. making a flow routing decision (DecisionState)

Flow definition

Spring Web Flow Version 1.0 RC1 9

Page 14: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

4. spawning another flow as a subflow (SubflowState)

5. terminating a flow (EndState)

Each of these state types, with the exception of EndState, is transitionable. This hierarchy is illustrated below:

State class diagram

2.6.1. ViewState

When entered, a view state allows the user (or other external client) to participate in a flow. This participationprocess goes as follows:

1. The entered view state makes a org.springframework.webflow.ViewSelection that selects a logicalresponse to issue with the data necessary to issue it.

2. The flow execution 'pauses' in this state, and control is returned to the calling system.

3. The calling system uses the returned ViewSelection to present an interface (or other response) to the user.

4. After some 'think time', the user submits an input event to resume the flow execution from the 'paused'point.

Spring Web Flow gives you full control over the view selection process and, on resume, how a view stateresponds to an user input event. It's important to understand that Spring Web Flow does not care for response

Flow definition

Spring Web Flow Version 1.0 RC1 10

Page 15: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

rendering--as a controller, a flow makes logical view selections when user input is required. It is up to thecalling system to issue a response suitable for the environment in which the flow is executing.

The properties of a org.springframework.webflow.ViewState are summarized below:

Table 2.5. ViewState properties

Property name Description Cardinality Default value

viewSelector The strategy that makes the view selectionwhen this state is entered.

0..1 Null

The properties of a org.springframework.webflow.ViewSelection are summarized below:

Table 2.6. ViewSelection properties

Property name Description Cardinality Default value

viewName The logical identifier of a response thatshould be issued.

1

modelMap The data that will be issued in theresponse.

0..* Empty

redirect Requests whether a browser redirectshould be triggered.

1 False

2.6.1.1. ViewSelector

The creational strategy that is responsible for making a ViewSelection when an ViewState is entered isorg.springframework.webflow.ViewSelector. This provides a plugin-point for customizing how theviewName is calculated, how the modelMap is prepared, and whether a redirect should be issued.

Two ViewSelector implementations are provided with Spring Web Flow:

Table 2.7. ViewSelector implementations

Implementation Description

SimpleViewSelector Returns a ViewSelection with a static viewName and modelMap

containing the union of the attributes in flow scope and request scope.Supports setting a requestConversationRedirect flag that triggers abrowser redirect to the selected view. The default implementation.

RedirectViewSelector Returns a ViewSelection that triggers a browser redirect to an abitraryexternal URL. The viewName is the relative URL to redirect to.Attributes added to the modelMap become URL query parameters.Mainly used by end states to redirect after flow completion.

The class diagram below shows the ViewState and the associated types used to carry out the view selectionprocess:

Flow definition

Spring Web Flow Version 1.0 RC1 11

Page 16: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

ViewState class diagram

2.6.1.2. ViewState XML - simple view selection

The following example shows a view-state definition in XML that makes a simple view selection whenentered, selecting the searchForm view for display and, on resume, responding to two possible user inputevents (submit and cancel) in different ways:

<flow start-state="displaySearchForm"><view-state id="displaySearchForm" view="searchForm">

<transition on="submit" to="processFormSubmission"/><transition on="cancel" to="processCancellation"/>

</view-state>

...</flow>

2.6.1.3. ViewState API - simple view selection

The following example shows the equivalent view state definition using the FlowBuilder API:

public class SearchFlowBuilder extends AbstractFlowBuilder {public void buildStates() {

addViewState("displaySearchForm", "searchForm",new Transition[] {

transition(on("submit"), to("processFormSubmission")),transition(on("cancel"), to("processFormCancellation"))

});

...}

}

Flow definition

Spring Web Flow Version 1.0 RC1 12

Page 17: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

2.6.1.4. ViewState XML - conversation redirect

The following example illustrates a view-state definition in XML that makes a simple view selection whenentered, redirecting to the yourList view for display.

<flow start-state="displayList"><view-state id="displayList" view="yourList" redirect="true">

<transition on="add" to="addListItem"/></view-state>

...</flow>

This is example is called a conversation redirect because the ViewSelection made is cached between request asthe "current view selection" for the active conversation. The actual redirect sent is a conversation URL thatrenders the current view selection on a request into the server.

2.6.1.5. ViewState API - conversation redirect

The following example shows the equivalent view state definition using the FlowBuilder API:

public class SearchFlowBuilder extends AbstractFlowBuilder {public void buildStates() {

addViewState("displayList", new SimpleViewSelector("yourView", true),transition(on("add"), to("addListItem"))

);...

}}

2.6.1.6. ViewState XML - form state behavior

The following example illustrates a view-state definition in XML that encapsulates typical "form state"behavior.

Consider the requirements of typical input forms. Most forms require pre-render or setup logic to executebefore the form is displayed. For example, such logic might load the backing form object from the database,install formatters for formatting form field values, and pull in supporting form data needed to populatedrop-down menus.

In addition, most forms require post-back or submission logic to execute when the form is submitted. This logictypically involves binding form input to the backing form object and performing type conversion and datavalidation.

This "form state" behavior of form setup, display, and post-back is handled elegantly in Spring Web Flow bythe capabilities of the view-state construct. See below:

<flow start-state="displayForm"><view-state id="displayForm" view="form">

<entry-actions><action bean="formAction" method="setupForm"/>

</entry-actions>

<transition on="submit" to="saveForm"><action bean="formAction" method="bindAndValidate"/>

</transition></view-state>...

Flow definition

Spring Web Flow Version 1.0 RC1 13

Page 18: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

</flow>

This reads "when the displayForm state is entered, execute the setupForm method on the formAction andrender the form view. On submit transition to the saveForm state if the bindAndValidate method on theformAction executes successfully."

2.6.2. ActionState

When entered, an action state executes business application code, then responds to the result of that executionby deciding what state in the flow to enter next. Specifically:

1. The entered action state executes an ordered list of one or more org.springframework.webflow.Action

instances. This Action interface is the central abstraction that encapsulates the execution of a logical unitof application code.

2. The state determines if the outcome of the first action's execution matches a transition. If there is a match,the transition is executed. If there is no match, the next action in the list is executed. This processcontinues until a transition is matched or the list of actions is exhausted.

Spring Web Flow gives you full control over implementing your own actions and configuring when they shouldbe invoked within the lifecycle of a flow. The system can also automatically adapt methods on your existingapplication objects (POJOs) to the Action interface in a non-invasive manner.

The properties of a org.springframework.webflow.ActionState are summarized below:

Table 2.8. ActionState properties

Property name Description Cardinality Default value

actions The ordered list of actions to executewhen the state is entered.

1..*

2.6.2.1. Action execution points

As outlined, the ActionState is the central state type for invoking one or more actions and responding to theirresult to drive a state transition. There are also other points within the lifecycle of a flow where a chain ofactions can be executed. At all of these points the only requirement is that these actions implement the centralorg.springframework.webflow.Action interface.

Table 2.9. Points in a Flow where an Action can be executed

Point Description

on flow start Each time an execution of a flow starts.

on state entry Each time a state enters.

on transition Each time a state transition is matched but before it is executed.

on state exit Each time a transitionable state exits.

on flow end Each time an execution of a flow terminates.

Flow definition

Spring Web Flow Version 1.0 RC1 14

Page 19: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

2.6.2.2. Action properties

An Action may be annotated with properties by wrapping the Action in a decorator, an instance oforg.springframework.webflow.AnnotatedAction. These properties may provide descriptive characteristics,or may be used to affect the action's execution in a specific usage context.

Support for setting several common properties are provided for convenience. These include:

Table 2.10. Common Action properties

Property name Description

caption A short description about the action, suitable for display as a tooltip.

description A long description about the action, suitable for display in a text box.

name The name of the action, used to qualify the action's result event. Forexample, an Action named placeOrder that returns success would beassigned a result event identified by placeOrder.success. This allowsyou to distinguish logical execution outcomes by action, useful wheninvoking multiple actions as part of a chain.

method The name of the target method on the Action instance to invoke to carryout execution. This facilitates multiple action methods per Actioninstance.

resultName If the target method is an arbitrary public method that returns a value,this is the name of the attribute the value should be indexed under.

resultScope If the resultName property is specified, this is the scope the resultattribute should be indexed in. For example, "request" or "flow" scope.

The class diagram below shows the ActionState and the associated types used to carry out the action executionprocess:

Flow definition

Spring Web Flow Version 1.0 RC1 15

Page 20: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

ActionState class diagram

2.6.2.3. ActionState XML - simple action execution

The following example constructs an ActionState definition from XML that executes a single action whenentered and then responds to its result:

<flow start-state="displaySearchCriteria">...<action-state id="executeSearch">

<action bean="searchAction"/><transition on="success" to="displayResults"/>

</action-state>...

</flow>

This state definition reads "when the executeSearch state is entered, execute the searchAction. On successfulexecution, transition to the displayResults state."

The association between the searchAction id and an Action implementation is made by the XmlFlowBuilderat Flow configuration time using a service registry, typically a Spring BeanFactory. For example:

<beans><bean id="searchAction" class="example.webflow.SearchAction"/>

</beans>

... associates the searchAction with a single instance of example.webflow.SearchAction.

A simple SearchAction implementation might look like this:

public class SearchAction implements Action {private SearchService searchService;

public SearchAction(SearchService searchService) {

Flow definition

Spring Web Flow Version 1.0 RC1 16

Page 21: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

this.searchService = searchService;}

public Event execute(RequestContext context) {// lookup the search criteria in "flow scope"SearchCriteria criteria =

(SearchCriteria)context.getFlowScope().getAttribute("criteria");

// execute the searchCollection results = searchService.executeSearch(criteria);

// set the results in "request scope"context.getRequestScope().setAttribute("results", results);

// return "success"return new Event(this, "success");

}}

2.6.2.4. ActionState API - simple action execution

The following example constructs the equivalent action state definition using the FlowBuilder API:

public class SearchFlowBuilder extends AbstractFlowBuilder {public void buildStates() {...addActionState("executeSearch", action("searchAction"),

transition(on("success"), to("displayResults")));...

}}

2.6.2.5. ActionState XML - action method execution

The next example constructs an ActionState definition from XML that executes a single action method on aorg.springframework.webflow.MultiAction and then responds to its result:

<flow start-state="displaySearchCriteria">...<action-state id="executeSearch">

<action bean="searchFlowAction" method="executeSearch"/><transition on="success" to="displayResults"/>

</action-state>...

</flow>

This state definition reads "when the executeSearch state is entered, execute the executeSearch method on thesearchFlowAction. On successful execution, transition to the displayResults state."

A SearchFlowAction implementation containing multiple action methods might look like this:

public class SearchFlowAction extends MultiAction {private SearchService searchService;

public SearchAction(SearchService searchService) {this.searchService = searchService;

}

public Event executeSearch(RequestContext context) {// lookup the search criteria in "flow scope"SearchCriteria criteria =

(SearchCriteria)context.getFlowScope().getAttribute("criteria");

Flow definition

Spring Web Flow Version 1.0 RC1 17

Page 22: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

// execute the searchCollection results = searchService.executeSearch(criteria);

// set the results in "request scope"context.getRequestScope().setAttribute("results", results);

// return "success"return success();

}

public Event someOtherRelatedActionMethod(RequestContext context) {return success();

}

public Event yetAnotherRelatedActionMethod(RequestContext context) {return success();

}}

As you can see, this allows you to define one to many action methods per Action class. With this approach,there are two requirements:

1. Your Action class must extend from org.springframework.webflow.MultiAction, or another class thatextends from MultiAction. The multi action cares for the action method dispatch that is based on thevalue of the method property.

2. Each action method must conform to the signature illustrated above: public Event

${method}(RequestContext) { ... }

2.6.2.6. ActionState API - action method execution

The following example constructs the equivalent action state definition using the FlowBuilder API:

public class SearchFlowBuilder extends AbstractFlowBuilder {public void buildStates() {...addActionState("executeSearch", method("executeSearch", action("searchAction")),

transition(on("success"), to("displayResults")));...

}}

2.6.2.7. ActionState XML - POJO action method execution

The next example constructs a ActionState definition from XML that executes a single method on your PlainOld Java Object (POJO) and then responds to the result:

<flow start-state="displaySearchCriteria">...<action-state id="executeSearch">

<action bean="searchService" method="executeSearch(${flowScope.criteria})"resultName="results"/>

<transition on="success" to="displayResults"/></action-state>...

</flow>

This state definition reads "when the executeSearch state is entered, execute the executeSearch method on thesearchService passing it the object indexed by name criteria in flowScope. On successful execution, exposethe method return value in request scope under the name results and transition to the displayResults state."

Flow definition

Spring Web Flow Version 1.0 RC1 18

Page 23: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

In this example, the referenced bean searchService would be your application object, typically a transactionalbusiness service. Such a service implementation must have defined the the Collection

executeSearch(SearchCriteria) method, typically by implementing a service interface:

public interface SearchService {public Collection executeSearch(SearchCriteria criteria);

}

With this approach there are no requirements on the signature of the methods that carry out action execution,nor is there any requirement to extend from a Web Flow specific base class. Basically, you are not required towrite a custom Action implementation at all--you simply instruct Spring Web Flow to call your businessmethods directly. The need the for custom "glue code" to bind your web-tier to your middle-tier is eliminated.

Spring Web Flow achieves this by automatically adapting the method on your existing application object to theAction interface and caring for exposing any return value in the correct scope.

This is adaption process is shown graphically below:

Bean->Action adapter

2.6.2.8. ActionState API - POJO action method execution

The following example constructs the equivalent action state definition using the FlowBuilder API:

public class SearchFlowBuilder extends AbstractFlowBuilder {public void buildStates() {

...addActionState("executeSearch", searchAction(),

transition(on("success"), to("displayResults")));...

}

protected Action searchAction() {AnnotatedAction searchAction =

method("executeSearch(${flowScope.criteria})", action("searchAction"));

Flow definition

Spring Web Flow Version 1.0 RC1 19

Page 24: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

searchAction.setResultName("results");return searchAction;

}}

2.6.3. DecisionState

When entered, a decision state makes a flow routing decision. This process consists of:

1. Evaluating one or more boolean expressions against the executing flow to decide what state to transition tonext.

2. Alternatively, executing a single decision action and evaluating its return event to decide what state totransition to next. This action should be idempotent; that is, it should not have side effects. Convenientsupport for evaluating return values of methods invoked on your application objects (POJOs) is provided.

The properties of a org.springframework.webflow.DecisionState are summarized below:

Table 2.11. DecisionState properties

Property name Description Cardinality Default value

action The idempotent action to execute whenthe state is entered. The action result eventis used as the basis for the decision.

0..1 Null

2.6.3.1. DecisionState XML - expression evaluation

The following example constructs an DecisionState from XML that evalutes a boolean expression todetermine what transition to execute:

<flow start-state="shippingRequired">

<decision-state id="shippingRequired"><if test="${flowScope.order.needsShipping} then="enterShippingDetails" else="placeOrder"/>

</decision-state>...

</flow>

This state definition reads "if the needsShipping property on the order object in flow scope is true, transitionto the enterShippingDetails state, otherwise transition to the placeOrder state."

Caution: flow definitions should not be vehicles for business logic. In this case the decision made wascontroller logic, reasoning on a pre-calculated value to decide what step of the flow to transition to next. That isthe kind of logic that should be in a flow definition. In contrast, having the state itself embed the business ruledefining how shipping status is calculated is a misuse. Instead, push such a calculation into application codewhere it belongs and instruct the flow to invoke that code using an action.

2.6.3.2. DecisionState XML - decision action

The following example constructs an DecisionState from XML that executes a action that forms the basis for

Flow definition

Spring Web Flow Version 1.0 RC1 20

Page 25: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

the transition decision:

<flow start-state="shippingRequired">

<decision-state id="shippingRequired"><action bean="shippingService" method="isShippingRequired"/><transition on="yes" to="enterShippingDetails"/><transition on="no" to="placeOrder"/>

</decision-state>...

</flow>

This state definition reads "if the isShippingRequired method on the shippingService returns true, transitionto the enterShippingDetails state, otherwise transition to the placeOrder state."

Note how the boolean return value of the isShippingRequired method is converted to the event identifiers yesor no.

This conversion process is handled by the action adapter responsible for adapting the method on yourapplication object to the org.springframework.webflow.Action interface. By default, this adapter applies anumber of rules for creating a result event from a method return value.

These conversion rules are:

Table 2.12. Default method return value to Event conversion rules

Return type Event identifier

boolean yes or no

java.lang.Enum this.name()

org.springframework.core.enum.LabeledEnum this.getLabel()

null null

You may customize these default conversion policies by setting a custom EventFactory instance on the beaninvoking action performing the adaption.

2.6.3.3. DecisionState XML - decision action with enum return value

The following example constructs an DecisionState from XML that executes a action that invokes a methodon an application object that returns a java.lang.Enum:

<flow start-state="shippingRequired">

<decision-state id="shippingRequired"><action bean="shippingService" method="calculateShippingMethod(${flowScope.order})"/><transition on="BASIC" to="enterBasicShippingDetails"/><transition on="EXPRESS" to="enterExpressShippingDetails"/><transition on="NONE" to="placeOrder"/>

</decision-state>...

</flow>

This state definition reads "if the getShippingMethod method on the shippingService returns BASIC for thecurrent order, transition to the enterBasicShippingDetails state. If the return value is EXPRESS transition to

Flow definition

Spring Web Flow Version 1.0 RC1 21

Page 26: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

the enterExpressShippingDetails state. If the return value is NONE transition to the placeOrder state."

2.6.4. SubflowState

When entered, a subflow state spawns another flow as a subflow.

Recall that a flow is a reusable, self-contained controller module. The ability for one flow to call another flowgives you the ability to compose independent modules together to create complex controller workflows. Anyflow can be used as subflow by any other flow, and there is a well-defined contract in play by what it means tobe a flow. Specifically:

1. A Flow is an instance of org.springframework.webflow.Flow.

2. A newly launched flow can be passed input attributes which it may choose to map into its own local scope.

3. An ending flow can return output attributes. If the ended flow was launched as a subflow, the resumingparent flow may choose to map the output attributes into its own scope.

It is helpful to think of the process of calling a flow as similiar to calling a Java method. Flows can be passedinput arguments and can produce return values just like methods can. Flows are more powerful because theyare potentially long-running, as they can span more than one request into the server.

The properties of a org.springframework.webflow.SubflowState are summarized below:

Table 2.13. SubflowState properties

Property name Description Cardinality Default value

subflow The definition of the flow to be spawnedas a subflow.

1

attributeMapper The strategy responsible for mappinginput attributes to the subflow andmapping output attributes from thesubflow.

0..* Null

When a SubflowState is entered, the following behavior occurs:

1. The state first messages its attributeMapper, an instance oforg.springframework.webflow.FlowAttributeMapper, to prepare a Map of input attributes to pass to thesubflow.

2. The subflow is spawned, passed the input attributes. When this happens, the parent flow suspends itself inthe subflow state until the subflow ends.

3. When the subflow ends, a result event is returned describing the flow outcome that occurred. The parentflow resumes back in the subflow state.

4. The resumed subflow state messages its attributeMapper to map any output attributes returned by thesubflow into flow scope, if necessary.

5. Finally, the resumed subflow state responds to the result event returned by the ended subflow by matching

Flow definition

Spring Web Flow Version 1.0 RC1 22

Page 27: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

and executing a state transition.

The constructs used in spawning a flow as a subflow is shown graphically below:

SubflowState class diagram

2.6.4.1. SubflowState XML - with input attribute

The following example constructs an SubflowState from XML that spawns a shipping subflow:

<flow start-state="enterOrderInformation">

...

<subflow-state id="enterShippingDetails" flow="shipping"<<attribute-mapper>

<input-attribute value="${flowScope.order.shipping}" name="shipping"/></attribute-mapper><transition on="finish" to="placeOrder"/>

</subflow-state>

...

</flow>

This subflow state definition reads "spawn the shipping flow and pass it the value of the shipping property onthe order object in flow scope as an input attribute with the name shipping. When the shipping flow ends,respond to the finish result event by transitioning to the placeOrder state."

Note how the inner structure and behavior of the shipping flow is fully encapsulated within its own flowdefinition. A flow calling another flow as a subflow can pass that flow input and capture its output, but itcannot see inside it. Flows are black boxes. Because any flow can be used as a subflow, it can be reused inother contexts without change.

2.6.4.2. SubflowState API - input attributes

The following illustrates the equivalent example using the FlowBuilder API:

Flow definition

Spring Web Flow Version 1.0 RC1 23

Page 28: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

public class OrderFlowBuilder extends AbstractFlowBuilder {public void buildStates() {

...addSubflowState("enterShippingDetails", flow("shipping"), shippingMapper(),

transition(on("finish"), to("placeOrder")));...

}

protected FlowAttributeMapper shippingMapper() {ParameterizableFlowAttributeMapper mapper = new ParameterizableFlowAttributeMapper();

mapper.addMapping("${flowScope.order.shipping}", "shipping");return mapper;

}}

2.6.5. EndState

When entered, an end state terminates a flow. A EndState represents exactly one logical flow outcome; forexample, "finish", or "cancel".

If the ended flow was acting as a top-level or root flow the entire flow execution ends and cannot be resumed.In this case the end state is responsible for making a ViewSelection that is the basis for the ending response(for example, a confirmation page, or a redirect request to an external URL).

If the ended flow was acting as a subflow, the spawned subflow session ends and the calling parent flowresumes by responding to the end result returned. In this case the responsibility for any ViewSelection falls onthe parent flow.

Once a flow ends any attributes in flow scope go out of scope immediately and become eligible for garbagecollection.

As outlined, an end state entered as part of a root flow messages its ViewSelector to make a ending viewselection. Typically this is a RedirectViewSelector, allowing for redirect after flow completion. An end stateentered as part of a subflow is not responsible for a view selection; this responsibility falls on the calling flow.

2.6.5.1. EndState result events

When a EndState is entered it terminates a flow and, if used as subflow, returns a result event the parent flowuses to drive a state transition from the calling subflow state. It is the end state's responsibility to create thisresult event which is the basis for communicating the logical flow outcome to callers.

By default, an EndState creates a result event with an identifier that matches the identifier of the end-state itself.For example, an end state with id finish returns a result event with id finish. Also by default, any attributes inflow scope that have been explicitly marked as output attributes are returned as result event parameters.

Spring Web Flow gives you full control over the ending view selection strategy, as well as what flow attributesshould be exposed as output on a per EndState basis. These configurable properties are summarized below:

Table 2.14. EndState properties

Property name Description Cardinality Default value

viewSelector The strategy that makes the ending viewselection when this state is entered and theflow is a root flow.

0..1 Null

Flow definition

Spring Web Flow Version 1.0 RC1 24

Page 29: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

Property name Description Cardinality Default value

outputAttributeNamesThe names of attributes in flow scope thatshould be exposed as output; thus beingmade eligible for output mapping by acalling flow.

0..* None

2.6.5.2. EndState XML - output attribute

The following example constructs an EndState from XML that terminates a shipping subflow:

<flow start-state="enterShippingDetails">

...

<end-state id="finish"<<output-attribute name="shipping"/>

</end-state>

</flow>

This end state definition reads "terminate the shipping flow and expose the shipping property in flow scope asan output attribute."

Since this end-state does not make a view selection it is expected this flow will be always used as a subflow.When this flow ends, the calling parent flow is expected to respond to the finish result, and may map theshipping attribute into its own scope.

2.6.5.3. EndState API - output attribute

The following illustrates the equivalent example using the FlowBuilder API:

public class ShippingFlowBuilder extends AbstractFlowBuilder {public void buildStates() {

...addEndState("finish", new String[] { "shipping" } );

}}

2.6.5.4. EndState XML - redirect after flow completion

The following example constructs an EndState from XML that terminates a shipping subflow and requests aredirect response to an external URL:

<flow start-state="enterOrderInformation">

...

<end-state id="finish" view="redirect:/orders/${flowScope.order.id}"/>

</flow>

This end state definition reads "terminate the order flow and request a redirect to the URL returned byevaluating the /orders/${flowScope.order.id} expression."

Flow definition

Spring Web Flow Version 1.0 RC1 25

Page 30: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

This is an example of the familiar redirect after post pattern where after transaction completion a redirect isissued allowing the result of the transaction to be viewed (in this case using REST-style URLs).

Flow definition

Spring Web Flow Version 1.0 RC1 26

Page 31: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

Chapter 3. Flow execution

3.1. Introduction

Once a flow has been defined any number of executions of it can be launched in parallel at runtime. Executionof a flow is carried out by a dedicated system that is based internally on a state machine that runs atop the JavaVM. As the the life of an flow execution can span more than one request into the server, this system is alsoresponsible for persisting conversational state across requests.

This chapter documents Spring Web Flow's flow execution system. You'll learn the core constructs of thesystem and how to execute flows within a variety of environments, including JUnit, Spring MVC, Struts, andJava Server Faces (JSF).

3.2. FlowExecution

An executing flow, an instance of org.springframework.webflow.execution.FlowExecution, represents the stateof a conversation at a point in time.

Spring Web Flow Version 1.0 RC1 27

Page 32: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

Chapter 4. Phonebook - a typical Spring Web Flowapplication

4.1. Introduction

This chapter explains some of the basic concepts of Spring Web Flow to you, using the Phonebook sampleapplication distributed with the Spring Web Flow release. The phonebook application incorporates one of themost often found flows in web applications; i.e. the search + master/detail flow. In the next couple of sections,we will explain how to build that flow using Spring Web Flow. Let's first discuss a good process for buildingflows into your web application:

1. The first step in the process of adding a flow to your application is to actually design the flow.Storyboarding the flow helps here with simple sketches (and/or) a state diagram

2. The next step is to create the configuration for the Flow. The configuration should reflect the flow you'vepreviously drawn on paper for example.

3. After you've created the configuration for the flow, it's time to test the execution of the flow. This can bedone using implementations of actions that haven't been fully completed yet.

4. After you've ensured the flow executes correctly, you can implement the logic encapsulated in your flowby completing the action classes you've added to your flow configuration. In other words: the Actionclasses are the place where you can implement logic and they somewhat resemble Spring MVC controllers(in fact, they can be Spring MVC controllers or action-like artifacts from any other MVC framework).

5. The last thing you need to do before you can deploy your flow is to implement the views for your flow.The views are the individual pages presented to the user. So remember: the views are the places whereusers are allowed to interact with the flow.

6. Deploy the flow for in-container testing. Of course there is nothing out-of-the-ordinary here, it's justdeploying your WAR file for example to a servlet container or application server.

Note that of course, some of these steps can happen in parallel; coding of artifacts such as Action classes canperfectly be done right along with implementing your view resources (JSP, Velocity templates, et cetera).

4.2. Designing the flow

As we've said, we're going to implement a simple phonebook application that will allow a user to search for aspecific person's information, view that information and edit it.

4.2.1. A small narrative

Let's start with a small narrative that completely lays out our flow.

1. View a search page where the user can enter the criteria he or she wishes to use for locating people.2. From the search page a submit button triggers the process of transferring the criteria to the server, binding

those criteria to a form backing object and validating the criteria. For a validation error the user will beredirected back to the search page. If however validation succeeds, the actual search will be executed.After the search has completed the user will be able to view the list of people that have been found (on theresults page).

3. From the results page the user can select one of the people that have been found based on the searchcriteria and view their details on the details page. Details in this case are things like the person's name,

Spring Web Flow Version 1.0 RC1 28

Page 33: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

contact information and people the person works with (colleagues).4. From the details page the user will be able to select a colleague and view their respective information on

another details page and after that go back to the previously selected person.

Note: some of the text in the description above is printed in bold. These (usually) verbs translate directly to theevents that will be signaled or the actions that will have to be executed in the flow. Later on, we'll explain inmore details what these events and actions really mean.

4.2.2. Graphical representation of our flow

After we've written down our flow, we can also storyboard it a bit. The storyboard helps us identifying possiblebottlenecks in the flow and see if it's complete.

The storyboard-version of our flow

Another way to put it, is a state diagram. The following diagram depicts our flow in somewhat more detail.

Phonebook - a typical Spring Web Flow application

Spring Web Flow Version 1.0 RC1 29

Page 34: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

State diagram of the phonebook flow (maybe update state diagram)

The state diagram above provides the most detailed glimpse into the design of the Flow: from it, you see all thestates of the flow, what actions occur at what state, and the transitions between states.

4.2.3. Web flow: a state machine

You'll see shortly that a flow implementation maps very elegantly from such a diagram. Indeed, if youunderstand the picture above, you understand Spring Web Flow. Specifically:

• Flow definitions have one or more states, one of which is marked the start-state.• Each state, when entered, executes some kind of action. What action is executed varies based on the state's

type and is executed in polymorphic fashion. For example, a view state renders a view resource. An actionstate executes a controller Action. sub-flow states spawn sub flows (so flows are reusable). End statesterminate an active execution of a flow (later on called a FlowExecution).

• Each state has one or more transitions. A transition is a path from one state to another. A transitionexecutes on the signaling of an event.

In general, when a user enters the flow (typically by clicking a link leading him to the flow or by opening uphis or her browser with a particular URL) a new flow is started, specifically for this user. This is what we callthe FlowExecution. The flow (obviously) starts in the start state.

There are several state types. The first (and this is what our flow starts with) is the view state. The view stateallows users to interact with the flow. Typically a view state is a web page with for example a form. Nothinghappens, until the user indicates he wants to move forward in the flow (by filling out a form and clicking the

Phonebook - a typical Spring Web Flow application

Spring Web Flow Version 1.0 RC1 30

Page 35: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

submit button for example). Clicking the submit button signals an event. The event (received by the server) willbe translated to a transition of the flow to a different state (of course predefined in the flow). In other words, theFlowExecution (remember: this is the execution of the flow for this specific user) has gotten a new active state.

The second state is an action state. Whereas view states allow for user interaction, action states don't. Theyexecute actions on the server, for example the binding of the form data to a form backing object, or theexecution of a search query.

Apart from those, there are several other state types which we'll describe in more detail in other chapters of thisreference manual.

Remember: both action states and view states can signal events, causing a transition to happen.

When applying this to the phonebook application, we end up with the following: The user starts the flow withthe View Search Criteria state. This will render the search page, with a form and a submit button. When theuser signals the submit event in the View Search Criteria state (by clicking the submit button), he willtrigger a transition to the Execute Query state (which, as we'll see actually comprises a couple of differentsteps all with the different possible outcomes). The Execute Query state is an action state. When the Execute

Query state completes successfully (binding and validation both complete without errors and the querying hasbeen executed) another event is signaled, causing the FlowExecution to move to the next state, in this case theView Results state. This process of event -> state transition -> new state (either action or view) continuesuntil an end state has been reached and the FlowExecution terminates.

4.3. Configuring the flow implementation using Java or XML

So now we've got the design for the flow fleshed out and we can start creating the configuration for our flow.One thing we didn't yet explain is sub flows. When a user views a person's details and clicks on a colleaguename, what he's actually doing is entering the same state the flow has been in before, but now for a differentperson (retrieve users details, view user details). Because this process can be repeated over and over again, weare going to model this as a sub flow. A sub flow is a reusable flow that can be spawned from a parent flow.

So what we need is a top-level search flow and a person detail flow that we're going to embed in our top-levelsearch flow.

Configuring flows can be done in both Java and XML. You can use whatever you prefer and we're going toshow you both ways in a minute. For more information about the different ways to configure your flows usingflow builders, refer to other parts of the reference manual, where the so-called XmlFlowBuilder and theAbstractFlowBuilder are explained in more detail.

4.3.1. Configuring the flow in XML

Let's first configure the phonebook flow in XML. Spring Web Flow features a dedicated XML format entirelydeveloped to express web flows in. The file we're creating is called search.xml meaning our flow will later onbe identified as search. First, we'll have to mention the DOCTYPE and start with identifying the start state ofthe flow. Remember: this is the initial state a flow will be in after it's been started.

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE flow PUBLIC "-//SPRING//DTD WEBFLOW 1.0//EN"

"http://www.springframework.org/dtd/spring-webflow-1.0.dtd">

<flow start-state="displayCriteria">

<!-- our flow goes here -->

</flow>

Phonebook - a typical Spring Web Flow application

Spring Web Flow Version 1.0 RC1 31

Page 36: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

After we've defined the start state (displayCriteria in this case), we need to start adding other states. Thesestates can be in any arbitrary order. In other words: the order in the XML file does not reflect the actual order orstates in the flow since the states are identified by a unique id. Of course it's handy to keep themwell-organized. The first state we're going to create is the start state. As we've seen in our state diagram, it's aview state and it's called displayCriteria. While defining the view state, we need to assign it an id. In thiscase, we're also assigning it a view identifier which in this specific case is resolved by a Spring MVCViewResolver. The skeleton for our state is ready.

<view-state id="displayCriteria" view="searchCriteria">

<!-- the remainder of the state definition goes here -->

</view-state>

The next thing we need to do is identify actions assotiated to the state and transitions that will allow the flow totransition to a different state. Each state can have actions assigned to it that will execute just before the state isentered into, as well as exit actions, executed right before the flow transitions to another state. In this specificexample, we're only using an entry action. The entry action is used set up the form the user will use to enter hissearch criteria in. More specifically, it calls a method on a action object specifically designed for formoperations that will set up the form backing object (i.e. the object the search criteria will be bound to later on).

The action object by the way is identified by the bean attribute. This attribute reflects a Spring IoC beanidentifier, meaning that this bean is a normal Spring-managed bean, defined elsewhere. When using SpringWeb Flow you don't necessarily have to work with Spring IoC, but in this example we do. In other words, thebean identified by the searchFormAction is a bean defined in a Spring ApplicationContext.

<entry-actions><action bean="searchFormAction" method="setupForm"/>

</entry-actions>

The last thing we need to do in order to get our first state working is to add one or more transitions that allowthe flow to transition to a different state. The only thing a user can do in this case really, is submit the form. Sowe add a transition that will fire when the search event is being signaled by the user (we'll see later on how toactually signal events to flows). When a different event is signaled, an exception will be raised. In this case, ifthe search event is signaled, the flow will transition to the executeSearch state if and only if the embeddedaction succeeds (more on how Web Flow decides whether or not to actually execute transitions can be found inother chapters of this reference manual). So in this case, if the bindAndValidate method succeeds (meaningbinding to the form object and validation of the form object succeeds) the transition will take place. In all othercases the transition won't take place and the flow will stick in its current state (causing the view to bere-rendered).

<transition on="search" to="executeSearch"><action bean="searchFormAction" method="bindAndValidate"/>

</transition>

The first state is done. We've gone through the entire process of creating a state, assigning it with an id,associating an entry action and a transition, along with a criteria for the transition to happen (or not). The nextthing we need to do is provide the next state in the flow. The previous state allowed for a user to enter somecriteria and submit them. Binding and validation will occur and depending on the result of this process(successful or unsuccessful) the transition will be executed. Let's not bother with the actual process of bindingand validation for now. This is something we'll explain later. Just imagine it automagically happens.

Phonebook - a typical Spring Web Flow application

Spring Web Flow Version 1.0 RC1 32

Page 37: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

Together with the view, the view state will result in the following screen being available (with the screenshowing a validation error in this case, indicating the user hasn't entered any criteria).

Validation errors while entering criteria

After validation has succeeded, the next state in our flow is the execution of the search, based on the searchcriteria the user has passed in. We can derive this from the to-attribute of the transition associated to the firststate we've jotted down. Execution of logic on the server, comprised in a separate step, is implemented using anaction state. An action state is not very different from a view state; the difference being that an action state doesnot have a view associated with it. Instead it has a nested action that will execute. In other words, where theview state interacts with the user, the action executes logic on the server. In the phonebook example, the actionstate executes the actual search, based on criteria the user has given.

<action-state id="executeSearch">

<!-- actions go here -->

</action-state>

The action is again identified by a Spring bean identifier, hence defined in a Spring ApplicationContext.

<action bean="phonebook" method="search({flowScope.searchCriteria})" resultName="results"/>

The actual action in this case is the calling of a method called search with one parameter. This parameter is theform object, which will talk about later when implementing the Java classes needed for the phonebookapplication. All you need to know right now is the signature of the method:

public List search(SearchCriteria c);

The result of the method is automatically bound in the context of the flow, meaning that views rendered afterthis state will have access to it (if for example the application uses JSP, you can access the List returned by the

Phonebook - a typical Spring Web Flow application

Spring Web Flow Version 1.0 RC1 33

Page 38: Version 1.0 RC1springdeveloper.com/downloads/spring-webflow-reference.pdf · Preface Many web applications consist of a mix of free browsing, where the user is allowed to navigate

search by using EL: ${results}).

If the execution of the search method is successful (in other words: no exception has been raised), the flowtransitions to the next state. Why? Because together with the action (inside the action-state) we're alsomentioning a transition that says for every event called success we should go to the displayResults state.

<transition on="success" to="displayResults"/>

As we've said, the next state is the displayResults state. This is another view state, with this time, thesearchResults view resource associated to it, as well as a different transition to the next state. Remember thattransitions are signaled by events and since this is a view state, the user will interact with the system. Bysignaling a select event, the flow will transition to the next state (browsing user details).

<view-state id="displayResults" view="searchResults"><transition on="newSearch" to="displayCriteria"/><transition on="select" to="browseDetails"/>

</view-state>

Phonebook - a typical Spring Web Flow application

Spring Web Flow Version 1.0 RC1 34