Servlets as Controllers

Servlets excel at complex logic,
but find presentation cumbersome
(all those out.println() statements).

That makes them natural controllers.

The Servlet as Controller:

  • Handles all incoming requests.
  • Analyzes the request parameters.
  • Determines which view to use.
  • Assembles the presentation data.
  • Sets attributes of the request.
  • Forwards the request to the view.
public class BlogServlet extends HttpServlet {
    private LogEntry[] entries;

    public void init() throws ServletException {
        loadEntries();
    }
    public void destroy() {
        saveEntries();
    }
    public void doGet( HttpServletRequest request, 
                       HttpServletResponse response) 
                       throws ServletException, IOException {
        RequestDispatcher dispatch;
        request.setAttribute("servletName", getServletName());

        String permalink = request.getParameter("permalink");
        String blogpost  = request.getParameter("blogpost");

        if (blogpost != null) {
            dispatch = request.getRequestDispatcher("/blogpost.jsp");
        } else if (permalink != null) {
            dispatch = request.getRequestDispatcher("/permalink.jsp");
            request.setAttribute("entries", getPLEntries(permalink));
        } else {
            dispatch = request.getRequestDispatcher("/blogshow.jsp");
            request.setAttribute("entries", entries);
        }

        dispatch.forward(request, response);
    }

    public void doPost( HttpServletRequest request, 
                       HttpServletResponse response) 
             throws ServletException, IOException {
        int      id       = getNextID();
        long     date     = new Date().getTime();
        String   author   = request.getParameter("author");
        String   title    = request.getParameter("title");
        String   entry    = mungeEntry(request.getParameter("entry"));
        LogEntry logEntry = new LogEntry(id, date, 
                                        author, title, entry);
        RequestDispatcher dispatch;
        request.setAttribute("servletName", getServletName());

        boolean preview  = (null != request.getParameter("preview"));
        
        if (preview) {
            request.setAttribute("entry", logEntry);
            dispatch = request.getRequestDispatcher("/blogpost.jsp");

        } else {
            addEntry(logEntry);
            request.setAttribute("entries", currEntries);
            dispatch = request.getRequestDispatcher("/blogshow.jsp");
        }

        dispatch.forward(request, response);
    }
}