Servlet Chains and Filters

So far, we have looked at servlets that take requests directly from the server and return their results directly to the client. Servlets were designed as a generic server extension technology, however, rather than one devoted solely to performing CGI-like functions. A servlet can just as easily take its input from another servlet, and a servlet really doesn’t care very much about where its output goes.

Most web servers that implement servlets have also implemented a feature called servlet chaining, where the server routes a request through an administrator-defined chain of servlets. At the end of the sequence, the server sends the output to the client. Alternately, some servers can be configured to route certain MIME types through certain servlets. If a filtering servlet is configured to take all of the output with the MIME type “servlet/filterme,” another servlet can produce data with that MIME type, and that data will be passed to the filtering servlet. The filtering servlet, after doing its work, can output HTML for the browser. MIME-based filtering also allows servlets to filter objects that don’t come from a servlet in the first place, such as HTML files served by the web server.

Example 5-5 demonstrates a basic servlet, derived from HttpServlet, that examines incoming text for a <DATE> tag and replaces the tag with the current date. This servlet is never called on its own, but instead after another servlet (such as an HTML generator) has produced ...

Get Java Enterprise in a Nutshell, Second 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.