|
|
Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs
You can use this article in two ways: to learn about some filters that are useful out of the box, or as an aid in writing your own filters. I'll start off with some simple examples and then move on to more advanced ones. At the end, I'll show you a file upload filter I wrote to support multipart requests.
In case you aren't yet familiar, a filter is an object that can transform a request or modify a response. Filters are not servlets; they don't actually create a response. They are preprocessors of the request before it reaches a servlet, and/or postprocessors of the response leaving a servlet. As you'll see later in the examples, a filter can:
You can configure a filter to act on a servlet or group of servlets. Zero or more filters can filter one or more servlets.
A filter implements javax.servlet.Filter and defines its three methods:
void init(FilterConfig config) throws ServletException: Called before the filter goes into service, and sets the filter's configuration object
void destroy(): Called after the filter has been taken out of service
void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException: Performs the actual filtering work
The server calls init(FilterConfig) once to prepare the filter for service, then calls doFilter() any number of times for requests specially set up to use the filter. The FilterConfig interface has methods to retrieve the filter's name, its init parameters, and the active servlet context. The server calls destroy() to indicate that the filter is being taken out of service. The filter lifecycle is now very similar to the servlet lifecycle
-- a change recently made in the Servlet API 2.3 Public Final Draft #2. Previously the lifecycle involved a setFilterConfig(FilterConfig)method.
In its doFilter() method, each filter receives the current request and response, as well as a FilterChain containing the filters that still must be processed. In the doFilter()method, a filter may do what it wants with the request and response. (It could gather data by calling their methods, or wrap
the objects to give them new behavior, as I'll discuss later.) The filter then calls chain.doFilter() to transfer control to the next filter. When that call returns, a filter can, at the end of its own doFilter() method, perform additional work on the response; for instance, it can log information about the response. If the filter wants
to halt the request processing and gain full control of the response, it can intentionally not call the next filter.