4. Code Example

Example 1. PersonController

The person controller still handles delete and search. It also has a newPerson() method used by the 'create' action-state in the person flow to put a new person in scope for the form.

                
@Controller
public class PersonController {

    final Logger logger = LoggerFactory.getLogger(PersonController.class);
    
    static final String SEARCH_VIEW_KEY = "/person/search";
    static final String SEARCH_MODEL_KEY = "persons";

    @Autowired
    protected PersonDao personDao = null;

    /**
     * Deletes a person.
     */
    @RequestMapping(value="/person/delete.html")
    public ModelAndView delete(@RequestParam("id") Integer id) {
        Person person = new Person();
        person.setId(id);
        
        personDao.delete(person);

        return new ModelAndView(SEARCH_VIEW_KEY, SEARCH_MODEL_KEY, search());
    }

    /**
     * Searches for all persons and returns them in a 
     * <code>Collection</code> as 'persons' in the 
     * <code>ModelMap</code>.
     */
    @RequestMapping(value="/person/search.html")
    @ModelAttribute(SEARCH_MODEL_KEY)
    public Collection<Person> search() {
        Collection<Person> lResults = personDao.findPersons();
        
        return lResults;
    }

    /**
     * Creates new instance of <code>Person</code>.
     */
    public Person newPerson() {
        return new Person();
    }

}
                
            

Example 2. PersonFlowHandler

At the end of the flow and when exception occurs that the flow doesn't handle, the PersonFlowHandler redirects to the search page.

                
@Component
public class PersonFlowHandler extends AbstractFlowHandler {

    /**
     * Where the flow should go when it ends.
     */
    @Override
    public String handleExecutionOutcome(FlowExecutionOutcome outcome,
                                         HttpServletRequest request, HttpServletResponse response) {
        return getContextRelativeUrl(PersonController.SEARCH_VIEW_KEY);
    }

    /**
     * Where to redirect if there is an exception not handled by the flow.
     */
    @Override
    public String handleException(FlowException e, 
                                  HttpServletRequest request, HttpServletResponse response) {
        if (e instanceof NoSuchFlowExecutionException) {
            return getContextRelativeUrl(PersonController.SEARCH_VIEW_KEY);
        } else {
            throw e;
        }
    }
    
    /**
     * Gets context relative url with an '.html' extension.
     */
    private String getContextRelativeUrl(String view) {
        return "contextRelative:" + view + ".html";
    }

}