He starts to build a bunch of servlets... one for each page

He considered having just a single servlet, with a bunch of if tests, but decided that separate servlets would be more OO—each servlet should have one responsibility like the query page, the sign-up page, the search results page, etc.

Each servlet will have all the business logic it needs to modify or read the database, and prints the HTML to the response stream back to the client.

// import statements

public class DatingServlet extends HttpServlet {

  public void doGet(HttpServletRequest request,
                 HttpServletResponse response)
                 throws IOException {

    // business logic goes here, depending
    // on what this servlet is supposed to do
    // (write to the database, do the query, etc.)

    PrintWriter out = response.getWriter();

    // compose the dynamic HTML page
    out.println( "something really ugly goes here");
  }
}
image with no caption
image with no caption

The servlet does whatever it needs to do to process the request (like insert or search the database) and returns the HTML page in the HTTP response.

All of the business logic AND the client HTML page response is inside the servlet code.

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.