public void setSearchBy(String searchBy) {
this.searchBy = searchBy;
}
}
}
Let’s chat a bit about this example, which highlights the strengths and weaknesses of this
Controllertype. A strength of this Controlleris that its superclass AbstractControllerpro-
vides helpful facilities such as enforcing allowed HTTP methods (as done in the constructor
in Listing 6-59). A shortcoming of this ability is that the allowed HTTP methods are common
across all request handlers inside the class, as there is no way to declaratively configure the
list of allowed request methods on a per–request handling basis. In this example, where all
requests are read-only, globally restricting to GET makes sense. If your MultiActionController
can handle different request methods at different times, you will have to declare those allowed
HTTP methods inside each handler method. For instance, the code from Listing 6-60 can be
used.
Listing 6-60.Ensure HTTP Methods
private void ensureMethod(HttpServletRequest request, String ... methods)
throws RequestMethodNotSupportedException {
for (String method : methods) {
if (request.getMethod().equals(method)) {
return;
}
}
throw new RequestMethodNotSupportedException("The request method " +
request.getMethod() + " is not allowed");
}
You can use such a method at the beginning of each request handling method (as shown
in Listing 6-61), but be sure to propagate the RequestMethodNotSupportedExceptionas the
superclass knows how to deal with it.
Listing 6-61.Example of Ensuring HTTP Method for a Request Handling Method
public ModelAndView findByUsername(HttpServletRequest request,
HttpServletResponse response, SearchCriteria criteria)
throws RequestMethodNotSupportedException {
ensureMethod(request, METHOD_GET);
Account account = accountService.findAccountByUsername(
criteria.getSearchBy());
return new ModelAndView("viewAccount", "account", account);
}
174 CHAPTER 6 ■THE CONTROLLER MENAGERIE