Expert Spring MVC and Web Flow

(Dana P.) #1
The lack of the presence of the Servlet API can be considered a benefit, as it makes it
easier to test this class. There is no need to create a MockHttpServletRequestjust to test the
controller.
When should you use this controller type instead of the others we’ve presented?
First off, if you find it convenient to treat the request as a true command object then the
ThrowawayControlleris exactly what you need. This style of controller makes it easy to route
the request around a system, with the ability to call methods on the controller and affect
its state. Second, if your controller is really simple and you don’t require access to the
HttpServletRequestand HttpServletResponseclasses, this class does allow for easier to
create tests.
You may not want to use this Controllerif the request is read-only and does not submit
any data. These cases usually do not require any state while performing the request, which
negates the need for a Command pattern implementation. Of course, you are free to imple-
ment every request handler with ThrowawayController, but the downside might be a higher
rate of garbage collection (which should only be a problem under very high loads).
Also, the ThrowawayControllerdoes not implement any form work flow, which makes it
more cumbersome to handle forms, validation, errors, and so on.

■NoteModern JVMs have sophisticated object creation and lifespan algorithms that can usually cope
with the constant creation of objects. The overhead of creating a new instance of ThrowawayControlleris
nearly negligible. As always, if under doubt, run your system with a profiler under heavy load and watch for
garbage collection performance.

Example
For an example of a ThrowawayController, we will add a CancelAccountController(Listing 6-75)
to the system. A form will request an Account’s username, and the Controllerwill attempt to
find the account and then cancel it.

Listing 6-75.CancelAccountController

public class CancelAccountController implements ThrowawayController {

private AccountService accountService;

private String username;

public void setUsername(String username) {
this.username = username;
}

public void setAccountService(AccountService accountService) {
this.accountService = accountService;
}

194 CHAPTER 6 ■THE CONTROLLER MENAGERIE

Free download pdf