Expert Spring MVC and Web Flow

(Dana P.) #1
Listing 4-8.HomeController

public class HomeController extends AbstractController {

private static final int FIVE_MINUTES = 5*60;
private FlightService flights;

public HomeController() {
setSupportedMethods(new String[]{METHOD_GET});
setCacheSeconds(FIVE_MINUTES);
}

public void setFlightService(FlightService flightService) {
this.flights = flightService;
}

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest req,
HttpServletResponse res) throws Exception {
ModelAndView mav = new ModelAndView("home");
mav.addObject("specials", flights.getSpecialDeals());
return mav;
}

}

The constructor configures this Controllerto respond only to HTTP GET requests,
because GET has semantics that most closely match that of “read.” In the case of a read-only
web page, such as the home page, this restriction prohibits potentially malicious clients from
exploiting the system in unintended ways.

■Tip For a full discussion on all of the available HTTP request methods and their semantics, consult section
9 of the HTTP RFC at http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html.The choice of
request method has a profound impact on application design and web architecture. Respond only to request
methods that are semantically appropriate—for example, GET for reads and POST for writes or modifications.

The constructor also instructs the superclass to send the appropriate HTTP headers to
enable caching. Thus, any caches or browsers that request the home page will be told it is
acceptable to cache the response for five minutes. Depending on the liveliness of your data,
this can be a simple way to reduce bandwidth and CPU cycles for your application. In our
case, the special deals won’t be changing faster than five minutes, so we are telling browsers
it’s OK to cache the home page for that long.

54 CHAPTER 4 ■JUMP INTO SPRING MVC

Free download pdf