Expert Spring MVC and Web Flow

(Dana P.) #1
public ModelAndView execute() throws Exception {
if (!StringUtils.hasText(username)) {
return new ModelAndView("cancelAccount", "errorMessage",
"Username must not be blank.");
}
try {
accountService.cancelAccount(username);
return new ModelAndView("cancelAccountSuccess");
} catch(AccountNotFoundException e) {
return new ModelAndView("cancelAccount", "errorMessage",
"No account found with username " + username);
}
}

}


Configuring this Controlleris similar to all other Controllers, except you must specify
singleton="false"in the bean definition. This will ensure a new instance is created for every
request. Otherwise, each request will use the same instance of the Controllerand risk
overwriting the property values. Listing 6-76 contains the bean definition for the
CancelAccountController.


Listing 6-76.CancelAccountController Bean Definition


<bean name="/cancelAccount" singleton="false"
class="com.apress.expertspringmvc.flight.web.CancelAccountController">




■CautionNeither the DispatcherServletnor the ThrowawayControllerHandlerAdapterwill pro-
vide a warning if the controller is a singleton, so double-check your ThrowawayControllers are indeed
prototypes.


It should be noted that the ThrowawayControllerrequires its own ThrowawayController➥
HandlerAdapterto function. If you have specified and configured one or more handler
adapters in your WebApplicationContext, you will need to also include ThrowawayController➥
HandlerAdapterif you choose to use that type of controller. By default, the DispatcherServlet
will include both SimpleControllerHandlerAdapterand ThrowawayControllerHandlerAdapter,
but it will ignore the defaults if at least one handler adapter is explicitly declared in the
WebApplicationContext.
As you can tell, there is no way to handle any sort of data binder errors inside
the Controller. If an error does occur, the ServletRequestBindingExceptionwill be
thrown by the handler adapter, and it will be left up to any exception resolvers found in the
WebApplicationContextto properly deal with the exception. This is probably not what you
want, so if a binding error could occur while populating the ThrowawayController, you will
need to instead implement a ValidatableThrowawayController(covered in the next section).


CHAPTER 6 ■THE CONTROLLER MENAGERIE 195
Free download pdf