Request dispatching for Beer Selector

Our Beer Selector is now up and running. But surely there could be a lot that could be done to improve it.

For instance, we notice that, even in such a simple example, relying on a servlet to generate the HTML required by the View is a clumsy, boring, error prone operation. It would be certainly be better to let a JSP page doing the best part of it.

That is what we are going to do here, using the request dispatching mechanism that is meant exactly for doing what we need in this context: calling a container-managed component (the new JSP page) from another container-managed component (our servlet).

In this way, we relieve the servlet of the view-related task and let it doing what is its real task, acting as a controller.

First task is creating the JSP page, result.jsp, that would actually display the result generated by the servlet.

We are expecting to find the suggested beers as a list in the request attribute named "beers". Before working on it, we ensure that the attribute exists and it is actually a List object, otherwise we signal the user we are having problems. Not a satisfactory answer, but better than displaying embarrassing internal error messages.
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page import="java.util.*" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Beer recommendations - JSP</title>
    </head>
    <body>
        <h1>Our beer recommendations:</h1>

        <%
            Object o = request.getAttribute("beers");
            if (o == null || !(o instanceof List)) {
                out.print("Sorry, we are experiencing problems. Try later.");
            } else {
                List beers = (List) o;

                Iterator it = beers.iterator();
                while (it.hasNext()) {
                    out.print("try: " + it.next() + "<br />");
                }
            }
        %>
    </body>
</html>
Our BeerSelector servlet is getting simpler. All the relevant code is now in the processRequest() method, that calls model object, BeerExpert, puts the result in the "beers" request attribute, and then passes the ball to the JSP page:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
    String color = request.getParameter("color");
    List<String> beers = new BeerExpert().getBrands(color);
    request.setAttribute("beers", beers);

    RequestDispatcher view = request.getRequestDispatcher("result.jsp"); // 1
    view.forward(request, response);
}
1. actually, getRequestDispatcher() could fail - result.jsp could not be currently available, for instance - so we should provide some error handling here.

This post has been originally written while I was reading the third chapter of Head First Servlet and JSP, a fun ad interesting book on Java EE.

No comments:

Post a Comment