Going with the Flow: Spring Web Flow
Friday, February 22nd, 2008 by Enrico
We recently worked on a short J2EE project using the Spring MVC framework. One of the models was particularly complicated, with multi-valued attributes that needed to be added, edited, and removed within the one form. The controller logic was starting to look like a complete mess of if-else statements as we tried to keep track of the current “state” of the form. What we had was, in effect, a poor man’s finite state machine. Then, we discovered Spring Web Flow.
Spring Web Flow can be integrated with Spring MVC to allow the creation of web flows. A flow is very much like a finite state machine — it has a set of states, including a starting state and (possibly) an ending state, and a set of transitions from each state. These states and transitions can be defined using XML or by pure Java code. The states can have Spring MVC views and/or actions associated with them. Actions can invoke form controller logic or call methods from other defined beans. This functionality is pretty slick in and of itself but the framework also provides for some very nice flow re-use. A flow can call on another flow, a sub-flow, to perform some actions and then resume when the sub-flow is finished. Error handling is also silly simple: provide a form-backing object and a validator and if there is an error binding to the form-backing object or validating its fields, the current state is invoked again with the same view. Special form tags can be used in the view to display errors that were raised. As the cherry on top, all of this can be done without breaking the browser’s back/forward button functionality.
The more I used this framework, the more I felt as though this is the way it should be done. Modeling user interactions with web applications as a finite state machine is very intuitive. I wish that this functionality were available for Ruby on Rails — actually, it could be greatly improved by using a Ruby-esque DSL instead of an XML syntax to define the flows! I recommend that anyone who is familiar with Spring but hasn’t tried Spring Web Flow yet try it today.



