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

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 ...

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