M anagi W eb Conversat ons ng i w i h Spri W eb Fl t ng ow

Keith Donald http://www.springframework.com keith@interface21.com

Agenda
      

History Motivation Positioning Architecture Walkthrough Issues and Solutions Conclusion

 Goals:
 

Understand Spring’s position in the web framework space See the value of Spring Web Flow (SWF) in action

H i ory – From Spri s st ng’ Perspect ve i
2000 Struts 2003 Spring MVC 2004 Ervacon Web Flows Fall 2005 Unified Spring Web Stack: Servlet MVC, Portlet MVC, Web Flow (SWF)

 Today, Struts is still the web framework

leader in terms of existing application deployments  Despite well-known limitations  Despite many challengers  The pragmatic majority is still waiting for the next dominant paradigm to emerge

Spri s W eb St ng’ ack M ot vat on i i
 To address the Struts pain points that are

hurting our customers  Spring MVC provides a better architecture without a high level of paradigm shock  To meet customer demand in places where it is clear Struts does not provide a solution  Spring has embarked into new territory  With its customers charting the course  Extracting new “whole products” to form a complete web stack

Product Posi i ng t oni
 A unified web stack, offering a one stop

shop for agile web application development  Respecting the existing Struts install base  Spring will continue to provide first class Struts support  Built from a set of modular, best-of-breed components  That can be integrated with other technologies where customers demand
• e.g. SWF is usable by JSF customers as a

NavigationHandler

TX. MGMT.g.Spri Cl t ng ari y Spring Web Stack Servlet MVC Portlet MVC Web Flow Remoting Spring Middleware Stack (IOC. and Excel views • Emerging web components include Valang for validation and DWR for AJAX . DAO. AOP. Spring MVC supports JSP. Jasper. Deploy) Each product in the stack integrates a number of components • e. Freemarker. Test. ORM. PDF. JCA) Spring AgileDev (Build.

M arket Expect i at ons  The current fragmentation in the web framework market will subside  Consolidation will happen  It’s already starting to  Spring will be a major player in the postshakeout. offering:  Maturity and synergy across the full stack  Low switching costs  Breakthrough technology  Professional support .

Breakt hrough Technol ogy .

Archi ect t ure  By example  Take a simple use case: A wizard for a phone operator to use to sell items to customers  Characteristics:  An “application transaction” that spans several steps  Some steps solicit user input  Some steps are decision points  Some steps perform calculations  Navigation from step-to-step is controlled  .

Create a session-scoped ActionForm to 2.H ow w oul you do t s t d hi oday w i h t St s? rut 1. hold the wizard form data Define a JSP for each step Define an Action for each step Expose each Action at a request URL Have the form rendered by the JSP submit to that URL At the end. 5. 4. delegate to a business service to commit the transaction . 3. 6.

do processTx confirmationPage Controller 3 Business Service .do updateForm page2 Controller 2 /lastStep.W hat t s l hi ooks lke i /step1.do page1 Controller 1 HTTP Session storeForm /step2.

Issues w i h t s approach t hi  Request centric: no concept of an ongoing         conversation or flow Brittle dependency on request URLs Manual state management Odd new window behavior Proper back button behavior is difficult “Loose” controlled navigation Difficult to observe process lifecycle Controller and command logic are coupled Heavily tied to HTTP .

Consequences  Many lines of custom code are      written to address these issues As an application grows more complex maintainability breaks down Fundamentally. something is missing Traditional approaches today lack a key abstraction: the Flow A Flow is typically longer than a single request but shorter than a session It is a conversation! .

bye! Friend (Melbourne. have you decided to just stay in Europe for good now? Keith: Life IS great here. Norway) Friend: Hello? Keith: Hi Friend! Friend: Hi Keith! So. Florida) .Fl Conversat on Anal ow i ogy Keith (Oslo. huh?  Keith: Gotta go.

W hat t SW F approach l he ooks lke i start “sell Item” firstPage store Flow Execution Storage submit nextPage load submit confirmationPage “Sell Item” FlowExecution .

the flow “pauses” and control returns to the client  Clients “signal” events to tell the flow what happened  The flow responds to events to decide what to do next  What to do next is fully encapsulated  Flows are modular “black boxes” .Si fcant archi ect gnii t ural dif f erences  One flow drives the entire conversation  When user input is required.

Fl Execut on St e Transi i ow i at t on Di agram start Created Ending end Active subflow spawned user input needed Paused user event signaled Resuming .

Q uest on i Q: How do you program the Flow? Q: How does it know what to do in response to user events? A: You create a Flow definition .

Fl D efni i St ow i t on ruct ure  A Flow definition serves as instructions to a finite state machine  It consists of a set of states that you define  Each state executes a polymorphic behavior when entered  View states solicit user input  Action states execute commands  Subflow states spawn child flows  End states terminate flows  Events you define drive state transitions .

The “Sel It ” Fl D efni i l em ow i t on start Enter Price and Item Count Enter Shipping Information submit submit yes Select Item Category submit Is Shipping Required? no Process Sale View State Action State Decision State End State Show Cost Overview .

see presentation notes  Demo of the Flow Execution .Code Break!  The “Sell Item” Flow Definition  If viewing on-line.

readable Navigation rules are encapsulated in one place No dependency on any request URLs Navigation is strictly enforced State management is automatic Flow lifecycle is fully observable Controller logic is clearly decoupled from command logic  The Flow is the controller. deciding what state to enter next  States execute arbitrary behavior when entered  HTTP independent  Flow definitions are extremely toolable        .Advant ages The logical flow is clearly defined.

W al hrough: Spri Ai kt ng r The best way to learn is by example  The airline industry:  Trip booking system  This vertical slice must:  1. Collect passenger information 5. Book the trip! . Assign seats 4. Obtain Trip Information 2. Suggest suitable itineraries 3.

Code Break!  The “Booking Agent” business façade  Subsystem boundary  The model context  The façade integration tests .

Expressi t booki fow ng he ng l .

Java-based.Buidi t Booki Fl D efni i l ng he ng ow i t on  First select a FlowBuilder strategy   XML. Custom Perhaps with a supplemental drag ‘n drop tool Define the behavior to happen when each state is entered Define the supported transitions from one state to another • Transitions map the paths through the Flow  Then create the states of the flow   .

Code Break!  The Booking Flow Definition  The Booking Flow Action  The Action Unit Tests  The Flow Execution Integration Tests  The View Templates  Application Deployment Configuration .

The Booki Fl D efni i ng ow i t on <webflow id="booking“ start-state=“displayTripForm"> <! – state definitions go here  </webflow> .

Renderi t Tri Form ng he p  Display the “trip form” so the user can tell the flow where she wants to go <view-state id="displayTripForm" view="tripForm"> <entry> <action bean="bookingFlowActions" method="setupForm"/> <action bean="formUtilityActions" method="setupDateChooser"/> </entry> <transition on="go" to="suggestItineraries"> <action bean="bookingFlowActions" method="bindAndValidate"/> </transition> </view-state> .

Suggest ng Tri It nerari i p i es  Suggest the best itineraries: <action-state id="suggestItineraries"> <action bean=“bookingActions"/> <transition on="success“ to="displaySuggestedItineraries"/> </action-state>  Action states invoke methods on Actions when entered  Can also directly invoke methods on POJOs  Example:  Entering “suggestItineraries” invokes the “suggestItineraries” method on the action identified by “bookingActions” .

getFlowScope(). private BookingAction(BookingAgent agent) { setFormObjectName("trip"). setFormObjectClass(Trip.bookingAgent = agent.getFlowScope().setAttribute("itineraries". Collection<Itinerary> itineraries = bookingAgent. return success(). } // other action methods related to the booking process… public Event book(RequestContext context) { … } } .The Booki Act on ng i Im pl ent i em at on public class BookingAction extends FormAction { private BookingAgent bookingAgent. } public Event suggestItinenaries(RequestContext context) { Trip trip = (Trip)context. context.suggestItineraries(trip). this. itineraries).getAttribute("trip").class).

Sel i an It nerary ect ng i  Display the itineraries and let the customer select one: <view-state id="displaySuggestedItineraries" view="suggestedItineraries"> <transition on="startOver" to="cancel"/> <transition on="select" to=“recordSelectedItinerary"/> </view-state> <action-state id=“recordSelectedItinerary"> <action bean=“bookingActions"/> <transition on="success" to="isPassengerInfoRequired"/> </action-state>   The flow pauses while the view is displayed for user “think time” The flow resumes in the same state on the next request (“post back”) to decide where to go next .

enter it.D eci ng w here t go next di o  Is passenger information required? If so. go straight to verification <action-state id=“isPassengerInfoRequired”> <transition on=“yes” to=“enterPassengerInformation”/> <transition on=“no” to=“displayReservationVerification”/> </action-state>  A logical decision point: “routing state”  A Decision State could have also been used . If not.

passing it the passenger ID if they have authenticated <subflow-state id="enterPassengerInformation" flow="passenger"> <attribute-mapper> <input value="${requestScope. .Ent ng Passenger Inf eri orm at on i  Spawn the “enter passenger information” process as a subflow. When the subflow ends. the parent responds to its result.passenger.id}“ as=“id”/> </attribute-mapper> <transition on="finish" to="displayReservationVerification"/> </subflow-state>  Note: the parent flow suspends while the subflow executes.

Then book the reservation! <view-state id="displayReservationVerification" view="reservationVerification"> <transition on="startOver" to="cancel"/> <transition on="assignSeats" to="chooseSeatAssignments"/> <transition on="book" to="book"/> </view-state> <action-state id="book"> <action bean=“bookingFlowActions"/> <transition on="success" to="displayConfirmation"/> </action-state> <end-state id="displayConfirmation" view="reservationConfirmation"/>   The end state terminates the flow when entered All flow resources are automatically cleaned up .Fi i ng t Reservat on nalzi he i  On verification. optionally choose seat assignments.

springframework.XmlFlowFactoryBean"> <property name="location“ value="classpath:/flows/booking.htm“ class="org.FlowController"/> <bean id="booking“ class="org.web.flow.config.mvc.xml"/> </bean>  One Flow Controller can execute all flows for the application at a single request URL  The views parameterize the controller with flow launching information  Security would be at the flow level .springframework.web.flow.D epl ng t Fl oyi he ow <bean name="/springair.

airport”/> <input type=“text” name=“dest.htm?_flowId=booking&src.airport”/> … <input type=“hidden” name=“_flowId” value=“booking”/> <input type=“submit” value=“Submit”/> </form>  Using an anchor: <a href="<c:url value="/springair.Exam pl vi s l e: ew aunchi fow s ng l  Using a form: <form method=“post” action=“springair.htm”/> <input type=“text” name=“src.airport=MLB& dest.airport=ATL"/>"> Launch Booking Flow </a> .

htm”/> <input type=“text” name=“firstName”/> <input type=“text” name=“lastName”/> … <input type=“hidden” name=“_flowExecutionId” value=“${flowExecutionId}”/> <input type=“submit” name=“_eventId_submit”/> </form>  Using an anchor: <a href="<c:url value="/springair.Exam pl es: vi s part ci i i ew i pat ng n fow s l  Using a form: <form method=“post” action=“springair.htm?_flowExecutionId=${flowExecutionId} & _eventId=submit&firstName=Keri&lastName=Donald/>“>Enter Passenger Information</a>  Each flow is assigned a unique identifier made available to the views for storage .

)  Duplicate submits   End States are one answer Redirects are another TransactionSynchronizer <end-state id=“end” view=“redirect:springair. flow storage and restoration   A stateful system brings challenges in a stateless environment Continuations provide a solution • Server-side session-based storage • Client-side seralization using hidden form field • Custom (database. etc.Issues and Sol i ut ons  Browser navigation button use.html?flowId=anotherFlow”/> • Token-based implementation relies on a secure token to be  present on the client and in flow scope • Interface is pluggable • Support for compensating transactions is of high interest to us: ended flow “rollback” . file.

Issues and Sol i ut ons  Responding to the lifecycle of an executing flow   Listeners may be attached to executing flows Callbacks are made on: • Request submitted – good for pre-flow event processing • Session starting – good for precondition checks • Session started -.good for post condition checks • Paused – good for custom view pre-render logic • Resumed – good for pre-flow event processing • State Entering – good for precondition checks • State Entered – good for post condition checks • Ended – good for custom cleanup logic • Request processed – good for post processing logic .

Issues and Sol i ut ons  Annotating a Flow with metadata  Any flow definition artifact can be annotated: • • • • Flow State Transition An action’s use in a action state  Example: <action-state=“book”> <property name=“role” value=“passenger” type=“grantedAuthority”/> <action bean=“bookingAction”> <property name=“caption” value=“Books the reservation”/> </action> </action-state> .

Issues and Sol i ut ons  Integrating into other environments   Create a specialized FlowController for that environment For example: • The FlowAction for Struts • The FlowNavigationHandler for JSF • The PortletFlowController for Portlets  Spring Web Flow is not coupled with any other web framework  Not even Spring MVC or the Servlet API  Proven in a Portlet environment  Truly an embeddable component .

events happens. • Book a trip • Pay your taxes • Apply for a Loan  Encapsulates that business goal as a reusable module • A “black box”  Often has multiple paths to support different scenarios • Paths may vary based on contextual information  Often spawns other Flows as sub flows • Has a clear. observable lifecycle: Flow executions start.g. they end .D esi Ti gn ps  What makes a good Web Flow?  Accomplishes some business goal. e.

D esi Ti gn ps  What doesn’t make a good Flow? Index pages  Welcome Pages  Menus  Simple Form Submissions (Mailers.)  Sites with a lot of free navigation  Web flows are best suited for enforcing controlled navigation to support business process workflows  As a compliment to traditional controllers  Don’t abuse them  . etc.

parallel sub flows .Spri W eb Fl Road M ap ng ow  JSF integration  JMX-enabled flow management  Ajax support  Asynchronous View State Actions  More configuration defaults  Research in the area of compensating transactions  Research in the area of asynchronous.

Resources and U pcom i Event ng s  www.springframework.org  New CMS portal means we now bring you a lot more content  Web Flow Wiki provides a “Quick Start”  Practical guide  Articles  Web Flow Ships with 7 sample applications  Phone Book (Core sample)  Sell Item (Wizard with Continuations)  Birth Date (Struts integration)  Item List (Transaction Synchronization)  Number Guess (Example of conversation history)  Flow Launcher (How to launch flows)  File Upload (A flow to upload files) .

i21 CEO) Juergen Hoeller (Spring Co-Founder. Process.springframework. Europe www. Beyond J2EE Featuring • • • • •  Super early bird registration period open now Rod Johnson (Spring Founder. Bal Harbour Beach Florida 40+ technical sessions across four tracks: Web. Pro Spring) … and many more .thespringexperience.com/training International conference for agile Java developers http://www. Enterprise. Sheraton Resort. 2005. i21 Chief Scientist) Rob Harrop (Author. i21 CTO) Adrian Colyer (AspectJ Founder.com December 7 – 10th.Resources and U pcom i Event ng s  Public Spring Training         The Spring Experience 4-day “bootcamps” across North America.

Thi Bi The Spri Experi nk g: ng ence 2005 .

3 will be a major upgrade to the Spring web stack Spring will continue to innovate Spring will continue to simplify .Concl on usi  Spring is a complete. pragmatic     full-stack application framework It adds serious value in:  The middle tier  The web tier Spring 1. modular.

Q uest ons? i .

Sign up to vote on this title
UsefulNot useful

Master Your Semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master Your Semester with a Special Offer from Scribd & The New York Times

Cancel anytime.