The servlet servlet API has long been the cornerstone of enterprise application development, while servlet filters are a relatively new complement to the Java family. This article introduces you to the Servlet filter architecture, defines many of the filters ' applications, and guides you through the three steps of a typical filter implementation. This article also reveals some of the exciting changes in the bean, which are expected to be introduced in the Java Servlet 2.4 specification just released.
Servlet filters are pluggable Web Components that allow us to implement preprocessing and post-processing logic in Web applications. Filters support the basic request processing capabilities of servlet and JSP pages, such as logging, performance, security, session processing, XSLT transformations, and so on. The filter was originally published with the Java Servlet 2.3 specification, and the recently finalized 2.4 specification has significantly upgraded it. Here I will introduce you to the basics of the servlet filter-for example, the overall architecture design, implementation details, and typical applications in Java EE WEB applications, as well as some of the extensions that are expected to be provided by the latest Servlet specification.
What is a Servlet filter?
Servlet filters are small WEB components that block requests and responses to view, extract, or manipulate data exchanged between clients and servers in some way. Filters are WEB components that typically encapsulate functionality, which, while important, is not conclusive for processing client requests or sending responses. Typical examples include logging data about requests and responses, handling security protocols, managing session properties, and so on. Filters provide an object-oriented modular mechanism for encapsulating common tasks into pluggable components that are declared by a configuration file and processed dynamically.
The Servlet filter combines a number of elements to make the filter a unique, powerful, and modular Web component. In other words, the Servlet filter is:
- declarative : Filters are declared through XML tags in the WEB deployment descriptor (web.xml). This allows you to add and remove filters without changing any application code or JSP pages.
- Dynamic : The filter is called by the Servlet container at run time to intercept and process requests and responses.
- Flexible : Filters are widely used in Web processing environments, covering many of the most common ancillary tasks, such as logging and security. Filters are also flexible because they can be used to perform preprocessing and post-processing of direct calls from clients, and to handle requests for scheduling between WEB components behind a firewall. Finally, you can link the filter to provide the necessary functionality.
- Modular : By encapsulating application processing logic into a single class file, the filter defines a modular unit that can easily be added or removed from the request/response chain.
- Portable: Like many other aspects of the Java platform, Servlet filters are portable across platforms and across containers, further supporting the modular and reusable nature of Servler filters.
- Reusable : Thanks to the modular design of the filter implementation class and the declarative filter configuration, filters can be easily used across different projects and applications.
- transparent : Includes filters in the request/response chain, designed to complement, rather than replace in any way, the core processing provided by a servlet or JSP page. As a result, filters can be added or removed as needed without destroying servlet or JSP pages.
So a Servlet filter is a modular reusable component that is flexibly declared through a configuration file. Filters dynamically handle incoming requests and outgoing responses, and they can be added or removed transparently without modifying the application code. Finally, the filters are independent of any platform or Servlet container, allowing them to be easily deployed into any compatible Java environment.
In the next few sections, we will look further at the overall design of the Servlet filter mechanism and the steps involved in implementing, configuring, and deploying the filter. We will also explore some of the practical applications of the servlet filter, and end with a brief review of the servlet filters contained in the model-view-controller (MVC) architecture, thus ending the discussion in this article.
Servlet Filter Architecture
As its name implies, the Servlet filter is used to block incoming requests and/or outgoing responses and to monitor, modify, or somehow process the data stream that is passing through. Filters are self-contained, modular components that can be added to the request/response chain or deleted without affecting other WEB components in the application. Filters are only run-time processing of change requests and responses and should not be embedded directly in the WEB application framework unless they are implemented through a well-defined standard interface in the Servlet API.
Web resources can be configured to have no filters associated with them (this is the default), associated with a single filter (this is typical), or even associated with a filter chain. So what exactly does a filter do? Like a servlet, it accepts requests and responds to objects. The filter then checks the request object and decides to forward the request to the next component in the chain, or aborts the request and sends a response directly back to the client. If the request is forwarded, it is passed to the next resource in the chain (another filter, servlet, or JSP page). After this request manages to pass through the filter chain and is processed by the server, a response is sent back through the chain in the reverse order. This gives each filter the opportunity to process the response object as needed.
When filters are introduced for the first time in the Servlet 2.3 specification, they can only filter the content between the Web client and the specified Web resources accessed by the client. If the resource then dispatches the request to another Web resource, the filter cannot be applied to any requests that are commissioned behind the scenes. The 2.4 specification eliminates this limitation. Servlet filters can now be applied anywhere in the Java WEB environment where requests and response objects exist. Therefore, a servlet filter can be applied between a client and a servlet, between a servlet and a servlet or a JSP page, and between each JSP page that is included. This is what I call power and flexibility!
Implement a Servlet filter
They say "strewn". I don't know who "they" are, or how true this old proverb is, but implementing a Servlet filter does take three steps. The first step is to write a program for the filter implementation class, and then add the filter to the Web application (by declaring it in the Web Deployment descriptor/web.xml), and finally package and deploy the filter with the application. We will look at each of these steps in detail.
1. Programming the Implementation class
The filter API contains 3 simple interfaces (again the number 3!). , which are neatly nested in the javax.servlet
package. That 3 interfaces are Filter
, and respectively FilterChain
FilterConfig
. From a programmatic point of view, the filter class implements the Filter
interface and then uses the interface in the filter FilterChain
class FilterConfig
. A reference to the filter class is passed to the FilterChain
object to allow the filter to pass control over to the next resource in the chain. The FilterConfig
object is provided by the container to the filter to allow access to the initialization data for that filter.
To be consistent with our three-step model, the filter must use three methods to fully implement the Filter
interface:
init()
: This method is invoked when the container instantiates the filter, and is primarily designed to prepare the filter for processing. This method takes an FilterConfig
object of a type as input.
doFilter()
: The service()
doPost()
doGet()
filter has a single method for handling requests and responses--just as the servlet has a method that invokes or is used to process the request doFilter()
. This method accepts three input parameters: one ServletRequest
, response
and one FilterChain
object.
destroy()
: As you can imagine, this method performs any cleanup operations that may need to occur before automatic garbage collection.
Listing 1 shows a very simple filter that tracks the approximate time it takes to meet a client's WEB request.
Listing 1. A filter class implementation
Import javax.servlet.*;import java.util.*;import java.io.*;p ublic class Timetrackfilter implements Filter {private Fi Lterconfig filterconfig = null; public void init (Filterconfig filterconfig) throws servletexception {this.filterconfig = Filterconfig; public void Destroy () {this.filterconfig = null; public void Dofilter (ServletRequest request, servletresponse response, Filterchain chain) throws IOE Xception, servletexception {Date starttime, endtime; Double totaltime; StartTime = new Date (); Forward the request to the next resource in the chain Chain.dofilter (request, wrapper); --Process the response--\//Calculate The difference between the "Start Time" and "Time Endtime = n EW Date (); TotalTime = Endtime.gettime ()-starttime.gettime (); TotalTime = totaltime/1000; Convert from milliseconds to seconds stringwriter sw = new StriNgwriter (); PrintWriter writer = new PrintWriter (SW); Writer.println (); Writer.println ("==============="); WRITER.PRINTLN ("Total elapsed time is:" + TotalTime + "seconds."); Writer.println ("==============="); Log the resulting string writer.flush (); Filterconfig.getservletcontext (). Log (Sw.getbuffer (). toString ()); }}
The life cycle of this filter is very simple, anyway, let's study it:
Initialization of
When the container loads the filter for the first time, the init()
method is invoked. The class contains a reference to the object in this method FilterConfig
. Our filters do not actually need to do this because initialization information is not used here for demonstration purposes only.
Filtration
Most of the time the filter is consumed here. The doFilter()
method is called by the container, passing in a reference to the ServletRequest
, and object, respectively, to the request/response chain ServletResponse
FilterChain
. The filter then has the opportunity to process the request, pass the processing task to the next resource in the chain (by invoking FilterChain
the method on the object reference doFilter()
), and then handle the response when the filter is returned by processing control.
destructor
The container calls the method immediately before garbage collection destroy()
so that it can perform any necessary cleanup code.
2. Configure the Servlet filter
The filter is declared by the two XML tags in the Web.xml file. <filter>
the label defines the name of the filter and declares the implementation class and init()
parameters. <filter-mapping>
the label associates the filter with a servlet or URL pattern.
Listing 2 is an excerpt from a web.xml file that shows how to declare a filter's inclusion relationship:
Listing 2. Declare a filter in Web.xml
<filter> <filter-name>Page Request Timer</filter-name> <filter-class>TimeTrackFilter</filter-class></filter><filter-mapping> <filter-name>Page Request Timer</filter-name> <servlet-name>Main Servlet</servlet-name></filter-mapping><servlet> <servlet-name>Main Servlet</servlet-name> <servlet-class>MainServlet</servlet-class></servlet><servlet-mapping> <servlet-name>Main Servlet</servlet-name> <url-pattern>/*</url-pattern></servlet-mapping>
The code example above declares a filter ("Page Request Timer") and maps it to a servlet ("Main servlet"). The servlet is then defined with a mapping to send each request (specified by a wildcard) to the servlet. This is a typical mapping declaration for the controller component. You should pay attention to the order of these declarations, because you must not deviate from the order of these elements.
3. Deploy Servlet Filters
In fact, deploying filters with WEB applications does not involve any complexity at all. Simply include the filter class and other Web component classes together, and put the Web.xml file (along with the filter definition and filter mapping declaration) into the Web application structure as you normally do, and the servlet container will handle everything else after it.
Many applications of filters
Your ability to take advantage of filters in Java EE WEB applications is limited only by your own creativity and application design skills. You can use filters anywhere that is suitable for use in decorative filter mode or interceptor mode. Some of the most common applications of filters are as follows:
load : For all requests to reach the system, the filter collects information such as browser type, time of day, forwarding URL, and logs them.
Performance : Filters the content through the line and before the servlet and JSP pages are extracted, and then gets the response content, and converts the response content to a compressed format before it is sent to the client machine.
Security : The filter handles the administration of authentication tokens and appropriately restricts access to security resources, prompts the user for authentication and/or directs them to a third party for authentication. The filter can even manage access control lists (access controls LIST,ACL) to provide authorization mechanisms in addition to authentication. Placing security logic in a filter, rather than in a servlet or JSP page, provides a great deal of flexibility. During development, the filter can be closed (commented out in the Web.xml file). In production applications, the filter can be enabled again. You can also add multiple filters to increase the level of security, encryption, and the service that cannot be denied, depending on your needs.
Session handling : Mixing servlet and JSP pages with session-handling code can be a lot of trouble. Using filters to manage sessions lets Web pages focus on content display and delegate processing without worrying about the details of session management.
XSLT Transformations : Whether using mobile clients or xml-based WEB services, the ability to perform transformations between XML syntaxes without having to embed logic in an application is absolutely priceless.
Adapting filters to the MVC architecture
The model-View-controller (MODEL-VIEW-CONTROLLER,MVC) architecture is an effective design that has now been integrated into most popular WEB application frameworks, such as Jakarta Struts and turbine, as the most important design methodology. Filters are designed to augment the request/response processing flow of an MVC architecture. Whether the request/response occurs between the client and the server or between other components on the server, the filters are applied identically in the processing stream. From the perspective of MVC, the Scheduler component (which is either included in the Controller component or working with the controller component) forwards the request to the appropriate application component for processing. This makes the controller layer the best place to include the Servlet filter. By placing the filter in front of the controller component itself, the filter can be applied to all requests, or it can be applied to individual WEB components by placing it between the controller/scheduler and the model and controller.
The MVC architecture is widely disseminated and has good documentation, and the detailed discussion of MVC is not the content of this article, and interested readers can find the content themselves.
Conclusion
Although filters only appear for several years, they themselves have been embedded as a key component in all agile, object-oriented Java EE Web applications. This article introduces you to the use of the Servlet filter. This article discusses the advanced design of the filter, compares the current specification (2.4) and the previous (2.3) models, describes the exact steps involved in implementing the filter, and how to declare the filter in the Web application, and then deploy it with the application. This article also describes some of the most common applications of Servlet filters, and mentions how filters fit into the traditional MVC architecture.