Building and testing the model class

In MVC, the model tends to be the “back-end” of the application. It’s often the legacy system that’s now being exposed to the web. In most cases it’s just plain old Java code, with no knowledge of the fact that it might be called by servlets. The model shouldn’t be tied down to being used by only a single web app, so it should be in its own utility packages.

The specs for the model

- Its package should be com.example.model

- Its directory structure should be /WEB-INF/classes/com/example/model

- It exposes one method, getBrands(), that takes a preferred beer color (as a String), and returns an ArrayList of recommended beer brands (also as Strings).

Build the test class for the model

Create the test class for the model (yes, before you build the model itself). You’re on your own here; we don’t have one in this tutorial. Remember, the model will still be in the development environment when you first test it—it’s just like any other Java class, and you can test it without Tomcat.

Build and test the model

Models can be extremely complicated. They often involve connections to legacy databases, and calls to complex business logic. Here’s our sophisticated, rule-based expert system for the beer advice:

package com.example.model; import java.util.*; public class BeerExpert { public List getBrands(String color) { List brands = new ArrayList(); if (color.equals("amber")) { brands.add("Jack Amber"); brands.add("Red Moose"); } else { brands.add("Jail Pale Ale"); brands.add("Gout ...

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.