Spring Web Flow - PowerPoint PPT Presentation

About This Presentation
Title:

Spring Web Flow

Description:

The Web Flow Controller The component ... Unit testing the flow ... Building Blocks Flows States States Transitions Events Deterministic finite automata ... – PowerPoint PPT presentation

Number of Views:261
Avg rating:3.0/5.0
Slides: 83
Provided by: ltnLvaps
Category:

less

Transcript and Presenter's Notes

Title: Spring Web Flow


1
Spring Web Flow
2
Introduction
  • Spring Web Flow is a subproject of the popular
    Spring Framework

http//www.springframework.org/webflow
3
Introduction
  • Spring Web Flow allows to build high-level,
    reusable, self-contained controller modules
    called flows that are runnable in any environment

4
Flows
  • A flow defines a user dialog that responds to
    user events to drive the execution of application
    code to complete a business goal
  • Flows are defined
  • declaratively using a
  • rich domain-specific
  • language, like
  • XML (XSD)

5
Spring Web Flowmotivation
6
Motivation part1 - flow definition
  • Traditionally, defining the UI flow in a web
    application has been a less than intuitive
    process
  • Frameworks like Spring
  • Web MVC force to cut the
  • UI flow into individual
  • controllers and views
  • Disadvantage the overall UI flow is not at all
    clear from looking at the controller definitions

7
Motivation part1 - flow definition
  • The Spring Web MVC offers a slightly higher level
    of functionality - form controllers that
    implement a predefined work flow
  • SimpleFormController
  • AbstractWizardFormController
  • However, these are still hard coded examples of a
    more general work flow concept

Spring Web Flow
8
Spring Web Flow solution
  • Allows to represent the UI flow in a web
    application in a clear and simple way
  • The UI flow is clearly visible by looking at the
    web flow definition (XML file)
  • Web Flows can be designed to be self-contained ?
    modular design and reuse
  • Consistent web flow definition technique ?
    you're not forced into using specialized
    controllers for very particular situations

9
Motivation part2 - navigation
  • Typical web application have a mix of navigation
    requirements
  • Free navigations
  • Controlled flows
  • Each case bring their own design challenges

10
Free navigation
  • A set of pages connected by links
  • Accessing a link renders a public resource
  • Examples
  • Kursa lekciju saraksts
  • http//www.webkursi.lv/java-eim/de/index_lectures_
    lu.html
  • Otrais praktiskais darbs
  • http//www.webkursi.lv/java-eim/de/lab_mvc_portal.
    html
  • Users can access resources directly
  • Can bookmark or send to a friend

11
Controlled flows
  • A user task that spans more than one request
  • The task is the public resource
  • Examples
  • Registration
  • E-shop ordering
  • Accessing the task URL starts a new task
    execution
  • Local to the current users session
  • Intermediate steps of an execution are not
    bookmarked

12
Effect on design
  • Free navigation
  • Stateless
  • When invoked
  • Does work
  • Selects a view to render
  • All in one request
  • A controlled flow is more complex
  • Stateful
  • Guides the user through a task with a linear
    progression
  • Renders a view to solicit task input as required

13
Motivation part3 - scopes
  • Three different Servlet scopes that dictate the
    visibility and location of objects and attributes
    that are associated with request processing
  • Request
  • Session
  • Application

14
Request scope
  • Has the smallest lifetime
  • Is unique to each request from a browser
  • Will be discarded when the view is returned to
    the browser
  • Typically contains data sent from the browser
  • browser headings
  • request parameters

15
Session scope
  • Starts as soon as each unique browser accesses
    the server
  • Ends if the server hasnt received a request
    within a specified timeout or if explicitly
    destroyed
  • This scope allows objects to live across requests
  • Typically contains e.g. information about the
    current user
  • user details
  • authentication

16
Application scope
  • Lives for the duration of the web application
    deployment
  • Contains shared application components and
    configuration elements

17
The problem with scopes
  • Many use cases do not fit into the Servlet scopes
  • Use case span more than one page but do not
    require the longevity of the session
  • The Servlet specification is missing the concept
    of a conversational scope to support the
    execution of use cases that span multiple pages

18
Use cases and scopes
19
Session scope?
  • Why not store everything in the session and
    manually perform cleanups when the conversation
    ends?
  • Server affinity
  • Greatly increased memory footprint per user
  • Name space clashes
  • No vocabulary for process modelling

20
Spring solution
  • Spring Web Flow treats conversational scope as a
    first-level citizen
  • The core artefact within Spring Web Flow is the
    flow (or conversation)
  • Conversations can execute in parallel without
    intruding on each other
  • When the conversation has finished, all allocated
    resources are automatically cleaned up

21
Spring Web Flow characteristics
22
Spring Web Flow characteristics
  • Implementation agnostic
  • Abstracted away from the Servlet specification
  • Nothing web-specific about a flow definition
  • Developer is not presented with an
    HttpServletRequest or an HttpServletResponse

23
Spring best practices
  • Develop against interfaces ? plug in the most
    appropriate implementation
  • Favor integration with established technologies
  • Allow reusability from within other established
    web frameworks
  • Integrates with Struts, JSF and Portlet MVC
  • Facilitate test-driven development

24
Spring Web Flow characteristics
  • Low adoption overhead
  • SWF is self-contained ? little impact when
    introducing it on existing projects
  • Spring Web Flow is another Controller tool in the
    MVC toolbox
  • A major design goal of Spring Web Flow was to do
    one thing and do it well

25
Spring Web Flowarchitectural overview
26
Integration options
  • Spring Web Flow is very self-contained ?
  • the entry points to other frameworks are
    consistent

27
Inside the SWF System
  • A central FlowExecutionManager façade is
    responsible for launching executions of flows on
    behalf of clients
  • Flow executions new user conversations with the
    server
  • Each conversation is given its own local data
    structure, called flow scope

28
Where is flow scope stored?
  • Flow scope is stored in a repository
  • A number of repository implementations to support
    different usage scenarios
  • SimpleFlowExecutionRepository
  • ContinuationFlowExecutionRepository
  • ClientContinuationFlowExecutionRepository

http//en.wikipedia.org/wiki/Continuation
29
Building Blocks
  • With Spring Web Flow, the primary challenge for
    developers is the design and implementation of a
    flow definition
  • Web flow is composed of a set of states
  • Each state has one or more transitions that are
    used to move to another state
  • A transition is triggered by an event

30
Flows
  • A flow defines a conversation, or dialogue,
    between users and the server

31
States
  • The steps of a flow are called states.
  • Five core types of states
  • Action state
  • Executes application code, typically delegating
    to a business service in the middle tier
  • View state
  • Renders a view allowing the user to participate
    in the flow by entering data or viewing a message

32
States
  • Subflow state
  • Spawns another flow as a subflow
  • Decision state
  • Evaluates a condition to drive a transition to a
    new state
  • End state
  • Terminates a flow

33
Transitions
  • All states (except end states) are transtionable
    and maintain a set of one or more transitions
    that define allowed paths to other states
  • A transition is triggered on the occurrence of an
    event

34
Events
  • Nothing more than something that happens within
    a state
  • An event is treated as a state outcome that
    captures the logical result of a states
    execution
  • From the previous slide
  • The submit event communicates that a submit
    button was pressed as the outcome of a view state
  • The yes event communicates that a true result
    was returned when evaluating a condition as the
    outcome of a decision state

35
Deterministic finite automata
http//www.u.arizona.edu/miller/webthesis/mthesis
/node8.html
36
Sample Application
37
Sample Application - Phonebook
  • Allows to locate an employee of the company using
    some search criteria
  • Once the right person is found, it is possible to
    consult detailed information (phone, colleagues)

http//www.ervacon.com/products/swf/intro/index.ht
ml
38
Sources and deployed sample
  • Sources
    \spring-webflow-1.0.5\projects\spring-webflow-samp
    les\phonebook
  • Deployed sample
  • http//spring.ervacon.com/swf-phonebook/

39
Phonebook domain objects
  • Person - A simple JavaBean containing person
    details
  • SearchCriteria - A query object representing a
    search in the phonebook
  • SearchCriteriaValidator - A validator to validate
    a SearchCriteria object
  • Phonebook - Main business facade interface
  • public ListltPersongt search(SearchCriteria
    criteria)
  • public Person getPerson(Long id)
  • The StubPhonebook implementation of the Phonebook
    interface just hard-codes some dummy data

40
Spring Web MVC Setup
  • Need to configure /WEB-INF/web.xml
  • ContextLoaderListener - initializes the Spring
    Framework when web application is loaded by the
    servlet engine
  • DispatcherServlet - handles all requests matching
    the URL pattern .htm

41
ContextLoaderListener
  • ltcontext-paramgt
  • ltparam-namegtcontextConfigLocationlt/param-namegt
  • ltparam-valuegt
  • classpathorg/springframework/webflow/samples/pho
    nebook/stub/services-config.xml
  • lt/param-valuegt
  • lt/context-paramgt
  • ltlistenergt
  • ltlistener-classgt
  • org.springframework.web.context.ContextLoaderList
    ener
  • lt/listener-classgt
  • lt/listenergt

The root application context will be loaded from
the services-config.xml classpath resource
42
services-config.xml
The root web application context, defined in
services-config.xml configures business facade
the phonebook bean
  • lt?xml version"1.0" encoding"UTF-8"?gt
  • ltbeans xmlns"http//www.springframework.org/schem
    a/beans"
  • xmlnsxsi"http//www.w3.org/2001/XMLSchema-instan
    ce"
  • xsischemaLocation"http//www.springframework.org
    /schema/beans
  • http//www.springframework.org/schema/beans/spring
    -beans-2.0.xsd"gt
  • ltbean id"phonebook" class"org.springframework.we
    bflow.
  • samples.phonebook.stub.StubPhonebook"/gt
  • lt/beansgt

43
DispatcherServlet
  • ltservletgt
  • ltservlet-namegtphonebooklt/servlet-namegt
  • ltservlet-classgt
  • org.springframework.web.servlet.DispatcherServ
    let
  • lt/servlet-classgt
  • ltinit-paramgt
  • ltparam-namegtcontextConfigLocationlt/param-namegt
  • ltparam-valuegt
  • /WEB-INF/phonebook-servlet-config.xml
  • /WEB-INF/phonebook-webflow-config.xml
  • lt/param-valuegt
  • lt/init-paramgt
  • lt/servletgt
  • ltservlet-mappinggt
  • ltservlet-namegtphonebooklt/servlet-namegt
  • lturl-patterngt.htmlt/url-patterngt
  • lt/servlet-mappinggt

44
ViewResolver
  • lt?xml version"1.0" encoding"UTF-8"?gt
  • ltbeans xmlns"http//www.springframework.org/schem
    a/beans"
  • xmlnsxsi"http//www.w3.org/2001/XMLSchema-insta
    nce"
  • xsischemaLocation"http//www.springframework.or
    g/schema/beans http//www.springframework.org/sche
    ma/beans/spring-beans-2.0.xsd"gt
  • ltbean id"viewResolver" class"org.springframewo
    rk.web.servlet.
  • view.InternalResourceViewResolver"gt
  • ltproperty name"prefix" value"/WEB-INF/jsp/"/gt
  • ltproperty name"suffix" value".jsp"/gt
  • lt/beangt
  • lt/beansgt

45
  • Spring Web MVC
  • is configured!
  • Next lets integrate
  • Spring Web Flow!

46
The Web Flow Controller
  • The component that does integration is
  • org.springframework.webflow.executor.mvc.
    FlowController
  • This controller will handle all things Web Flow
    on behalf of the application
  • Configure in phonebook-servlet-config.xml

ltbean name"/phonebook.htm" class "org.springfram
ework.webflow.executor.mvc.FlowController"gt ltprope
rty name"flowExecutor" ref"flowExecutor"/gt lt/bea
ngt
47
Flow executor
  • All flow execution management responsibilities
    will be delegated to flow executor
  • phonebook-webflow-config.xml

lt?xml version"1.0" encoding"UTF-8"?gt ltbeans ...
gt ltflowexecutor id"flowExecutor"
registry-ref"flowRegistry"/gt
ltflowregistry id"flowRegistry"gt
ltflowlocation path"/WEB-INF/flows/-flow.xml
"/gt lt/flowregistrygt lt/beansgt
48
Flow registry
  • The flow registry will load flows from XML files
    found in the /WEB-INF/flows/ directory that have
    the -flow.xml suffix
  • The search flow defined in search-flow.xml will
    be assigned the id search-flow
  • The detail flow defined in detail-flow.xml will
    receive the id detail-flow

49
Request parameters
  • Web Flow controller is invoked by the dispatcher
    servlet to handle a request
  • It examines the following request parameters to
    determine what to do
  • _flowId
  • _flowExecutionKey
  • _eventId

50
_flowId
  • Id of a flow for which a new execution should be
    launched
  • Possible values in a sample application are
  • search-flow and detail-flow
  • If "_flowExecutionKey" parameter is not present,
    the flow controller launches a new flow execution
  • The new execution will be assigned a unique key

lta href"phonebook.htm?_flowIdsearch-flow"gtPhoneb
ooklt/agt
51
_flowExecutionKey
  • The unique id of an ongoing flow execution
  • When present in a request, the flow controller
    will restore the ongoing flow execution and
    resume it
  • The flow execution key is available in the
    request outcome model using the name
    "flowExecutionKey

ltinput type"hidden" name"_flowExecutionKey
value"flowExecutionKey"/gt
52
_eventId
  • The event that will be triggered in the current
    state of the flow
  • Is required when accessing an ongoing flow
    execution
  • Not used when launching a new flow execution

ltinput type"submit" class"button"
name"_eventId_search" value"Search"/gt
53
  • Now all the
  • infrastructure is in place!
  • Let's look at Web Flows and what they can do for
    us!

54
Web Flow schema
  • Technically, a Web Flow is nothing more than an
    XML file representation of the UI flow
  • Schema reference to indicate that an XML file
    contains a Web Flow definition

ltflow xmlns"http//www.springframework.org/schema
/webflow" xmlnsxsi"http//www.w3.org/2001/XMLSch
ema-instance" xsischemaLocation"
http//www.springframework.org/schema/webflow
http//www.springframework.org/schema/webflow/
spring-webflow-1.0.xsd"gt
55
Web Flow states
  • The Web Flow schema defines that a flow is
    composed of a set of states
  • Each state will have a unique id in the flow
  • Supported state types
  • start-state
  • action-state
  • view-state
  • decision-state
  • subflow-state
  • end-state

56
Event signaling
  • The way a state signals events depends on the
    state type
  • View state
  • Event is based on user input submitted to the
    controller using the "_eventId" request parameter
  • Action state
  • The executed actions signal events
  • Subflow state
  • Event is based on the outcome of the subflow they
    spawned

57
Search Flow (initial version)
lt?xml version"1.0" encoding"UTF-8"?gt ltflow
xmlns...gt ltstart-state idref"enterCriteria"/gt
ltview-state id"enterCriteria"
view"searchCriteria"gt lttransition on"search"
to"displayResults"/gt lt/view-stategt ltview-state
id"displayResults" view"searchResults"gt lttran
sition on"newSearch" to"enterCriteria"/gt lttran
sition on"select" to"...detail
module..."/gt lt/view-stategt lt/flowgt
  • Note flow does not define an end state!

58
Detail Flow (initial version)
lt?xml version"1.0" encoding"UTF-8"?gt ltflow
xmlns...gt ltstart-state idref"displayDetails
" /gt ltview-state id"displayDetails"
view"details"gt lttransition on"back"
to"finish" /gt lttransition on"select"
to"...detail module..." /gt lt/view-stategt
ltend-state id"finish" /gt lt/flowgt
  • In this case there is an end state since we need
    to end this flow and return to the calling flow
    when going back

59
Views
  • Web Flow definitions reference three views
  • "searchCriteria
  • ? /WEB-INF/jsp/searchCriteria.jsp
  • "searchResults"
  • ? /WEB-INF/jsp/searchResults.jsp
  • "details
  • ? /WEB-INF/jsp/details.jsp
  • Implementing SWF views is similar to any other
    Spring Web MVC application
  • The point of interest is linking back to the flow
    controller and signaling an event

60
searchCriteria.jsp
  • ltformform commandName"searchCriteria"
    method"post"gt
  • lttablegt
  • lttrgtlttdgtSearch Criterialt/tdgtlt/trgtlttrgtlttd
    colspan"2"gtlthr/gtlt/tdgtlt/trgt
  • ltspringhasBindErrors name"searchCriteria"gt
  • lttrgtlttd colspan"2"gt
  • ltdiv class"error"gtPlease provide valid search
    criterialt/divgt
  • lt/tdgtlt/trgt
  • lt/springhasBindErrorsgt
  • lttrgtlttdgtFirst Namelt/tdgtlttdgtltforminput
    path"firstName" /gtlt/tdgtlt/trgt
  • lttrgtlttdgtLast Namelt/tdgtlttdgtltforminput
    path"lastName" /gtlt/tdgtlt/trgt
  • lttrgtlttd colspan"2"gtlthr/gtlt/tdgtlt/trgt
  • lttrgtlttd colspan"2" class"buttonBar"gt
  • ltinput type"hidden"
  • name"_flowExecutionKey" value"flowExecutionK
    ey"/gt
  • ltinput type"submit"
  • class"button" name"_eventId_search"
    value"Search"/gt

61
Views (continued)
  • The "searchResults" view and the "details" view
    are very similar
  • Example from the "details" view that uses an
    anchor to submit the "select" event in the
    detail-flow

lta href"phonebook.htm? _flowExecutionKeyflowE
xecutionKey _eventIdselect idcolleague.id
"gt colleague.firstName colleague.lastName
ltbr/gt lt/agt
62
Actions
  • So far Web Flows just navigate between pages
  • To do some actual processing in a Web Flow, we
    need actions
  • Typical form processing
  • Pre-render logic prepare form before display
    (load)
  • Submit or postback logic actions than need to be
    executed on submit (bind, validate)
  • Backing form object object that will be edited
    in the form

63
Action interface
  • An action is a Java class implementing the
    org.springframework.webflow.execution.Action
    interface

public interface Action public Event
execute(RequestContext context) throws
Exception
  • Out-of-the-box action with HTML form handling
    functionality
  • org.springframework.webflow.action.FormAction

64
Action Execution Points
  • Action can be executed at the following points
    within the flow life cycle
  • On flow start
  • On flow end
  • On state enter
  • On state exit
  • Before transition

65
FormAction
  • Functionality is similar to the Spring
    BaseCommandController
  • Methods
  • setupForm()
  • prepare the Spring form handling machinery to
    properly display the form
  • bindAndValidate()
  • bind incoming request parameters to the form
    backing object and validate them

66
Adding actions to enterCriteria state
  • ltflow ...gt
  • ....
  • ltview-state id"enterCriteria" view"searchCriteri
    a"gt
  • ltrender-actionsgt
  • ltaction bean"formAction" method"setupForm"/gt
  • lt/render-actionsgt
  • lttransition on"search" to"displayResults"gt
  • ltaction bean"formAction" method"bindAndValid
    ate"/gt
  • lt/transitiongt
  • lt/view-stategt
  • ...
  • ltimport resource"search-flow-beans.xml"/gt
  • lt/flowgt

Need to configure formAction bean in
search-flow-beans.xml
67
formAction bean configuration
ltbeans xmlns...gt ltbean id"formAction"
class"org.springframework.webflow.action.FormActi
on"gt ltproperty name"formObjectClass"
value"org.springframework. webflow.samples.phon
ebook.SearchCriteria"/gt ltproperty
name"validator"gt ltbean class"org.springframewor
k.webflow.samples. phonebook.SearchCriteriaVali
dator"/gt lt/propertygt lt/beangt lt/beansgt
  • By default the form action will
  • store the form backing object in flow scope
  • assign it a name based on the class name
    "searchCriteria"

68
  • Form backing object
  • is configured!
  • Next need to invoke service
  • to perform the search!

69
Invoking service method
  • Spring Web Flow allows to directly call methods
    on any Spring managed bean from inside a Web Flow

ltview-state id"displayResults"
view"searchResults"gt ltrender-actionsgt
ltbean-action bean"phonebook" method"search"gt
ltmethod-argumentsgt ltargument
expression"flowScope.searchCriteria"/gt
lt/method-argumentsgt ltmethod-result
name"results"/gt lt/bean-actiongt
lt/render-actionsgt lttransition on"newSearch"
to"enterCriteria"/gt lttransition on"select"
to"...detail module..."/gt lt/view-stategt
70
Subflows
  • While the subflow is active, execution of the
    parent flow session is suspended and the subflow
    handles all requests
  • When the subflow reaches an end state, execution
    continues in the parent flow
  • The event signalled to continue the parent flow
    is the id of the end state that was reached in
    the subflow

71
Sample application subflows
  • There are two modules
  • search module and a detail module
  • Search flow will use the detail flow as a subflow
    to show person details
  • Detail flow will also use itself as a subflow to
    show colleague details
  • Detail flow is packaged as a reusable web
    application module ? can be reused easily

72
Subflow definition in search flow
  • ltflow xmlns...gt
  • ...
  • ltview-state id"displayResults"
    view"searchResults"gt
  • ...
  • lttransition on"select" to"browseDetails"/gt
  • lt/view-stategt
  • ltsubflow-state id"browseDetails"
    flow"detail-flow"gt
  • ltattribute-mappergt
  • ltinput-mappergt
  • ltmapping source"requestParameters.id"
  • target"id" from"string" to"long"/gt
  • lt/input-mappergt
  • lt/attribute-mappergt
  • lttransition on"finish" to"displayResults"/gt
  • lt/subflow-stategt
  • ...
  • lt/flowgt

73
Detail flow definition
  • ltflow xmlns...gt
  • ltinput-mappergt
  • ltinput-attribute name"id"/gt
  • lt/input-mappergt
  • ...
  • ltview-state id"displayDetails"
    view"details"gt
  • ...
  • lttransition on"select" to"browseColleagueDet
    ails" /gt
  • lt/view-stategt
  • ltsubflow-state id"browseColleagueDetails"
    flow"detail-flow"gt
  • ltattribute-mappergtltinput-mappergt
  • ltmapping source"requestParameters.id"
    target"id" from"string" to"long" /gt
  • lt/input-mappergtlt/attribute-mappergt
  • lttransition on"finish" to"displayDetails" /gt
  • lt/subflow-stategt
  • ...
  • lt/flowgt

74
Attribute mapper
  • Map model data from a parent flow to a subflow
    and back again
  • Mapping data to the subflow happens before the
    subflow session is started
  • Mapping data back is done when the subflow
    completes and the parent flow session resumes

75
  • Sample application
  • COMPLETED!

76
Unit testing the flow execution
  • Spring Web Flow provides flow unit testing
    support classes
  • This support includes
  • Convenient base classes for implementing flow
    execution tests
  • AbstractXmlFlowExecutionTests
  • Mock implementations of core Web Flow constructs
    such as the RequestContext to support unit
    testing flow artifacts such as Actions in
    isolation

77
Example flow unit test
  • public class SearchFlowExecutionTests extends
    AbstractXmlFlowExecutionTests
  • _at_Override
  • protected FlowDefinitionResource
    getFlowDefinitionResource()
  • return createFlowDefinitionResource(
  • "src/main/webapp/WEB-INF/flows/search-flow.xml"
    )
  • public void testStartFlow()
  • ApplicationView view applicationView(startFlow
    ())
  • assertCurrentStateEquals("enterCriteria")
  • assertViewNameEquals("searchCriteria", view)
  • assertModelAttributeNotNull("searchCriteria",
    view)
  • ...

78
Spring IDE Web Flow Visualizer
  • The Spring IDE Web Flow support allows developers
    to edit XML-based flow definitions graphically
  • Phonebook flow visualized
  • with the Spring IDE Web Flow
  • editor

http//www.springframework.org/node/429
79
Spring IDE Web Flow Visualizer
  • Auto-complete for state identifiers

http//www.springframework.org/node/429
80
Spring IDE Web Flow Visualizer
  • Auto-complete for beans in web and application
    service layers

http//www.springframework.org/node/429
81
Conclusion
  • Spring Web Flows important benefits
  • capture the UI flow in a clear and easily
    readable way
  • provide a consistent manner to model navigation
    throughout a web application
  • handle all navigational control, making sure
    applications works correctly even when the user
    uses back/refresh
  • allow to package a part of a web application as a
    self-contained, reusable module
  • offer sophisticated state management, providing
    several new scopes for conversation related data

82
References
  • Spring Web Flow Home http//www.springframework.or
    g/webflow
  • Spring Web Flow - A Practical Introduction
  • http//www.ervacon.com/products/swf/intro/index.h
    tml
  • Book Expert Spring MVC and Web Flow
    http//www.amazon.com/Expert-Spring-MVC-Web-Flow/d
    p/159059584X
  • Spring IDE Web Flow Visualizer
  • http//www.springframework.org/node/429
Write a Comment
User Comments (0)
About PowerShow.com