Skip to Content
Head First Servlets and JSP, 2nd Edition
book

Head First Servlets and JSP, 2nd Edition

by Bryan Basham, Kathy Sierra, Bert Bates
March 2008
Intermediate to advanced
911 pages
20h 31m
English
O'Reilly Media, Inc.
Content preview from Head First Servlets and JSP, 2nd Edition

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Head First Java, 2nd Edition

Head First Java, 2nd Edition

Kathy Sierra, Bert Bates
Head First Java, 3rd Edition

Head First Java, 3rd Edition

Kathy Sierra, Bert Bates, Trisha Gee
Learning Java, 6th Edition

Learning Java, 6th Edition

Marc Loy, Patrick Niemeyer, Daniel Leuck

Publisher Resources

ISBN: 9780596516680Errata PageSupplemental Content