But then it gets ugly, so he adds JSPs

Those pesky println() statements for the output response get really ugly, really quickly. So he reads up on JSPs and decides to have each servlet do whatever business logic it needs to do (query the database, insert or update a new record, etc.) then forward the request to a JSP to do the HTML for the response. This also separates the business logic from the presentation... and since he’s been reading up on design, he knows that separation of concerns is a Good Thing.

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

    // forward the request to a specific JSP page
    // instead of trying to print the HTML
    // to the output stream
  }
}
image with no caption
image with no caption
image with no caption

Client fills out the DQL query form and clicks the “Do it” button. This sends an HTTP POST request for the DoDQLQuery. The web server invokes the servlet, the servlet runs the query on the database, then the request is forwarded to the appropriate JSP. The JSP builds the response HTML ...

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.