Model for the Beer Selector

The toy beer selector described in the previous post gets here a bit more interesting, because we are adding to it a class acting as model, in the sense of the Model View Controller (MVC) pattern.

The class BeerExpert is about to do the magic of selecting a couple of beers accordingly to the color specified by the user.

In this naive implementation, our model is going to perform a real poor magic:
package model03;

import java.util.ArrayList;
import java.util.List;

public class BeerExpert {
    public List<String> getBrands(String color) {
        List<String> brands = new ArrayList<String>();
        if(color.equals("amber")) {
            brands.add("Jack Amber");
            brands.add("Red Moose");
        else {
            brands.add("Jail Pale Ale");
            brands.add("Gout Stout");
To use this model, we change slightly our controller:
public class BeerSelector extends HttpServlet {
    private BeerExpert expert = new BeerExpert();

    private void printAdvice(PrintWriter out, String color) {
        List<String> beers = expert.getBrands(color);
        Iterator<String> it = beers.iterator();
            out.println( + "<br />");

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        // ...
        out.println("Beer Selection Advice: <br />");
        // out.println("<p>Got beer color " + request.getParameter("color") +"</p>");
        printAdvice(out, request.getParameter("color"));
        // ...
We create a private method in the servlet, printAdivice(), that uses the BeerExpert to get the beers list and then writes them in the PrintWriter.

We just change a line in the processRequest(), instead of echoing the color passed to the servlet, we call the newly created printAdvice() method.

I wrote this post while reading the third chapter of Head First Servlet and JSP, a fun ad interesting book on Java EE.

No comments:

Post a Comment