Servlet APIs have long ago become the cornerstone of enterprise application development, while servlet filters are a relatively new supplement to the J2EE family. InJ2EE ExplorerIn the last article of the series, the author Kyle gabhart will introduce you to the servlet filter architecture, define many applications of filters, and guide you through the three steps of typical filter implementation. He will also reveal some exciting changes to bean, which are expected to be introduced in the newly released Java Servlet 2.4 specification.
Servlet filters are pluggable Web Components that allow us to implement preprocessing and post-processing logic in Web applications. Filters support basic request processing functions of Servlet and JSP pages, such as logging, performance, security, session processing, XSLT conversion, and so on. The filter was initially released along with the Java Servlet 2.3 specification, and was significantly upgraded by the recently finalized 2.4 specification. HereJ2EE ExplorerIn the last article of the series, I will introduce you to the basic knowledge of servlet filters, such as the overall architecture design, implementation details, and typical applications in J2EE Web applications, some extended functions that are expected to be provided by the latest servlet specifications will also be involved.
What is a servlet filter?
Servlet filters are small Web Components that intercept requests and responses to view, extract, or operate in some way the data being exchanged between the client and the server. Filters are Web Components that typically encapsulate some functions. These functions are important but not decisive for processing client requests or sending responses. Typical examples include recording data about requests and responses, processing security protocols, and managing session attributes. Filters provide an object-oriented modularization mechanism to encapsulate common tasks into pluggable components that are declared in a configuration file and processed dynamically.
Servlet filters combine many elements to make filters unique, powerful, and modular web components. That is to say, the servlet filter is:
- Declarative: The filter is declared by the XML tag in the Web deployment descriptor (Web. XML. This allows you to add and delete filters without modifying any application code or JSP pages.
- Dynamic: The servlet container calls the filter at runtime to intercept and process requests and responses.
- Flexible: Filters are widely used in Web processing environments and cover many of the most common auxiliary tasks, such as logging and security. Filters are flexible because they can be used to perform preprocessing and post-processing for Direct calls from clients and to process requests scheduled between Web components after the firewall. Finally, you can link the filter to provide the required functions.
- Modular: By encapsulating the application processing logic into a single class file, the filter defines modular units that can be easily added or deleted from the request/response chain.
- Portable: Like many other aspects of the Java platform, Servlet filters are portable across platforms and containers, further supporting the modularization and reusable nature of servler filters.
- Reusable: Thanks to the modular design of the filter implementation class and the declarative filter configuration method, the filter can be easily used across different projects and applications.
- Transparent: Include filters in the request/response chain, which is designed to supplement (rather than replace in any way) The core processing provided by the servlet or JSP page. Therefore, the filter can be added or deleted as needed without damaging the servlet or JSP page.
Therefore, Servlet Filters use a configuration file to flexibly declare modular reusable components. Filters dynamically process incoming requests and outgoing responses. They can be added or deleted transparently without modifying the application code. Finally, filters are independent from any platform or servlet container, allowing them to be easily deployed in any compatible J2EE environment.
In the following sections, we will further examine the overall design of the servlet filter mechanism and the steps involved in implementing, configuring, and deploying the filter. We will also discuss some practical application of servlet filters. Finally, we will briefly examine the servlet filters contained in the Model-View-controller (MVC) architecture, so as to end the discussion in this article.
Servlet filter architecture
As its name implies,Servlet FilterIt is used to intercept incoming requests and/or outgoing responses, and monitor, modify, or process data streams that are being passed in some way. Filters are self-contained and modular components that can be added to the request/response chain or deleted without affecting other Web Components in the application. Filters are only used to modify the runtime processing of requests and responses. Therefore, they should not be directly embedded into the web application framework, unless they are implemented through standard interfaces well defined in servlet APIs.
Web resources can be configured to be associated with no filters (this is the default situation), associated with a single filter (this is a typical situation), or even associated with a filter chain. So what exactly does the filter do? Like 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 abort the request and send a response directly to the client. If the request is forwarded, it is passed to the next Resource (another filter, Servlet, or JSP page) in the chain ). After the request is processed by the server through the filter chain, a response will be sent back through the chain in reverse order. This gives each filter the opportunity to process the response object as needed.
When filters are first introduced in the servlet 2.3 specification, they can only filter content between the Web Client and the specified Web Resource accessed by the client. If the resource then schedules the request to other web resources, you cannot apply the filter to any requests entrusted by the background. 2.4 The specification eliminates this restriction. Servlet filters can now be applied anywhere in the J2EE Web environment where request and response objects exist. Therefore, the servlet filter can be applied between the client and Servlet, between Servlet and servlet or JSP pages, and between each included JSP page. This is what I call powerful capabilities and flexibility!
Implement a servlet Filter
They say "everything is fine ". I don't know who "they" refer to, or how real the old saying is, but there are three steps to implement a servlet filter. First, you need to write a program that implements the filter class, and then add the filter to the Web application (by deploying the descriptor/web in the web. declare it in XML), and finally package and deploy the filter with the application. We will take a detailed look at each of these steps.
1. Compile the program for implementation class
The filter API contains three simple interfaces (Number 3 again !), They are neatly nested injavax.servlet
Package. The three interfaces areFilter
,FilterChain
AndFilterConfig
. From the programming point of view, the filter class will implementFilter
Interface, and then useFilterChain
AndFilterConfig
Interface. A reference of this filter class will be passedFilterChain
Object To allow the filter to pass control to the next resource in the chain.FilterConfig
The object will be provided to the filter by the container to allow access to the initialization data of the filter.
To be consistent with our three-step model, the filter must use three methods for full implementation.Filter
Interface:
init()
: This method is called when the container instantiates a filter. It is mainly designed to prepare the filter for processing. This method acceptsFilterConfig
Type object as input.
doFilter()
: Hasservice()
Method (this method is called againdoPost()
OrdoGet()
) To process requests, the filter has a single method for processing requests and responses --doFilter()
. This method accepts three input parameters: OneServletRequest
,response
And oneFilterChain
Object.
destroy()
: As you can imagine, this method performs any cleanup operations, which may need to be performed before automatic garbage collection.
Listing 1 shows a very simple filter that tracks the approximate time taken to satisfy a client's Web requests.
List 1. Implement a filter class
import javax.servlet.*;import java.util.*;import java.io.*;public class TimeTrackFilter implements Filter { private FilterConfig 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 IOException, 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 end time endTime = new 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 lifecycle of this filter is very simple. In any case, let's take a look at it:
-
Initialization
-
When the container loads the filter for the first time,
init()
The method is called. This class includes
FilterConfig
Object reference. Our filter does not actually need to do this, because initialization information is not used here, just for demonstration purposes.
-
Filter
-
Most of the time consumed by the filter is here.
doFilter()
The method is called by the container.
ServletRequest
,
ServletResponse
And
FilterChain
Object reference. The filter then has the opportunity to process the request and pass the processing task to the next resource in the chain (by calling
FilterChain
Object Reference
doFilter()
Method), and then process the response when the processing control returns the filter.
-
Structure Analysis
-
The container is called immediately before garbage collection.
destroy()
To execute any necessary cleanup code.
2. Configure the servlet Filter
The filter is declared through two XML tags in the web. xml file.<filter>
The tag defines the name of the filter and declares the implementation class andinit()
Parameters.<filter-mapping>
The tag associates the filter with the servlet or URL mode.
Listing 2 is taken from a Web. xml file and shows how to declare the inclusion relationship of a filter:
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 "). Then, a ing is defined for the servlet to send each request (specified by a wildcard) to the servlet. This is a typical ing Declaration of the Controller component. Pay attention to the order of these declarations, because the order of these elements cannot be deviated.
3. Deploy servlet Filters
In fact, deploying filters with Web applications does not involve any complexity. You only need to include the filter class and other Web component classes, and put the web as you normally do. XML files (together with the filter definition and filter ing Declaration) are put into the web application structure, and the servlet container will process all other things afterwards.
Many applications of filters
Your ability to use filters in J2EE Web applications is limited by your creativity and application design skills. You can use filters wherever you are applicable to the decorative filter mode or interceptor mode. Some of the most common applications of filters are as follows:
- Load: For all requests arriving at the system, the filter collects information such as the browser type, the time of the day, the forwarding URL, and logs them.
- Performance: The filter decompress the content when the content passes through the line and before arriving at the servlet and JSP pages, and then obtain the response content, and convert the response content to the compression format before it is sent to the client machine.
- Security: Filters manage authentication tokens and properly restrict access to security resources, prompting users to perform authentication and/or direct them to a third party for authentication. The filter can even manage the access control list (ACL) to provide authorization in addition to identity authentication. Putting the security logic in a filter, rather than on a servlet or JSP page, provides great 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 denial-of-service as needed.
- Session Processing: Mixing Servlet and JSP pages with Session processing code may cause considerable trouble. Using filters to manage sessions allows web pages to focus on content display and delegate processing without worrying about session management details.
- XSLT Conversion: Whether you use a mobile client or an XML-based Web Service, the ability to execute conversions between XML syntaxes without embedding logic into an application is absolutely priceless.
Adapt the filter to the MVC Architecture
The Model-View-controller (MVC) architecture is an effective design. It is now the most important design methodology, integrated into most popular Web application frameworks such as Jakarta Struts and turbine. The filter is designed to expand the request/Response Processing stream of the MVC Architecture. Whether the request/response occurs between the client and the server, or between other components on the server, the application of the filter in the processing stream is the same. From the MVC perspective, the Scheduler Component (which is included in the Controller component or works with the Controller component) forwards requests to appropriate application components for processing. This makes the Controller layer the best position to include servlet filters. By placing the filter in front of the Controller component itself, the filter can be applied to all requests, or by placing it between the Controller/scheduler and the model and the Controller, it can be applied to individual web components.
The MVC Architecture is widely spread and has good documentation. For more information about Servlet implementation in MVC and MVC architectures, see the link in references.
Conclusion
Although filters have been around for several years, they have been embedded into all agile, object-oriented J2EE Web applications as a key component. This article describes how to use servlet filters. This article discusses the advanced design of the filter, compares the current specification (2.4) with the previous (2.3) model, and describes the precise steps involved in implementing the filter, and how to declare a filter in a web application and deploy it with the application. This article also describes some of the most common application of servlet filters and introduces how filters adapt to the traditional MVC Architecture.
This isJ2EE ExplorerThe last article in the series. At the beginning of this year, we started our journey by studying the Enterprise JavaBean components, and mentioned the question of when to use these components to make sense and when these components will become useless. Then we looked at the web layer and drew a path through servlet, JSP page, JavaBean technology, and numerous choices and functions in Java Servlet API. In this series of articles, it is really a pleasure to walk on with you. I am enjoying the fun of writing this series of articles, and I know from your feedback that this is also a very valuable process for you. Thank you for your participation in this series of articles. Good luck and a happy exploration!
References
- Participate in the Forum on this article. (You can also clickDiscussionTo access the Forum .)
- Sun's J2EE tutorial is always a good place to learn about core J2EE technologies. For more information about servlet filters, see the section filter requests and responses.
- Sing Li's article "taming your Tomcat: filtering tricks for Tomcat 5 (DeveloperworksMarch 2003) is an excellent article on defining servlet filters in the Tomcat web environment.
- To learn the basics of servlet 2.3 filters, read the "The Essentials of filters" on java.sun.com ".
- Jason Hunter's "servlet 2.4: What's in store2.4" Article (JavaworldMarch 2003) is a comprehensive preview of the expected changes to the servlet 2.4 specification.
- Of course, you can always go to the source to read Java Servlet 2.4 specification.
- Visit the JCP Java Servlet 2.4 final release page and download the final version of the Java Servlet 2.4 specification.
- You can find a detailed introduction to Model-View-controller mode at www.encode.com.
- For a deeper understanding of MVC and a panoramic view specific to J2EE, analyze the Guidelines Excerpted from Sun Microsystems's "designing enterprise applications with the J2EE platform.
- It is better to use struts to design a servlet-centered method for MVC. You can use the "struts, an open-source MVC implementation "(DeveloperworksFebruary 2001) Understand all aspects of struts.
- Don't miss itJ2EE ExplorerAny issue in the series. See the complete list of Kyle gabhart's J2EE explorer column.
- In the IBM developerworks Java technology area, you can find hundreds of articles on various aspects of Java programming.
- Please visit developer bookstore for a detailed list of technical books, including hundreds of Java-related books.