O'Reilly logo

Head First Servlets and JSP, 2nd Edition by Bert Bates, Bryan Basham, Kathy Sierra

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Improving the MVC controllers

Besides a lack of cohesiveness, the controller is also tightly coupled to the model and the view components. And there’s yet another Duplicate Code Alert here. How can we fix things?

 

The controller’s three main tasks

A better way to handle it?

1

Get and deal with the request parameters

Give this task to a separate form validation component that can get the form parameters, convert them, validate them, handle validation errors, and create an object to hold the parameter values.

2

Invoke the model

Hmmm... we don’t like hard-coding the model into the controller, so maybe we could do it declaratively, listing a bunch of models in our own custom deployment descriptor that the controller could read and, based on the request, figure out which model(s) to use.

3

Dispatch to the View

Why not make this declarative as well? That way, based on the request URL, the controller can tell (from our custom deployment descriptor) which view to dispatch to.

New and (shorter) controller pseudo-code

public class ControllerServlet extends HttpServlet {

  public void doPost(request, response) {

    // call a validation component declaratively
    // (have it handle validation errors too!)

    // declaratively invoke a request processing
    // component, to call a Model component

    // dispatch to the view JSP declaratively
  }
}
image with no caption

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required