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

Get Head First Servlets and JSP, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.