Use Java Servlets 2.4 to perform filtering

xiaoxiao2021-03-06  61

The servlet API has long been the cornerstone of enterprise application development, and the servlet filter is a relatively new complement to the J2EE family. in

In the last article of the J2EE Explorer series, the author Kyle Gabhart will introduce you to the Servlet filter architecture to define many applications for filters, and guide you to complete three steps implemented by typical filters. He will also reveal some of the exciting changes in Beans, and it is expected that the Java Servlet 2.4 specification that is just released will introduce these changes.

The Servlet filter is an insertable web component that allows us to implement pre-processing and post-processing logic in a web application. Filters support basic request processing features for servlet and JSP pages, such as logging, performance, security, session processing, XSLT conversion, and more. The filter was originally published with the Java Servlet 2.3 specification, and the recent final draft 2.4 specification has been significantly upgraded. In the last article of this J2EE Explorer series, I will introduce you to the basics of the servlet filter - such as the overall architecture design, implementation details, and typical applications in the J2EE web application, will also involve Some expected extensions will be provided.

What is the servlet filter? The servlet filter is a small Web component that intercepts requests and responses to view, extract, or in some way that is being exchanged between clients and servers. The filter is a web component that typically encapsulates some features, which is important, but is not decisive for processing client requests or sending responses. Typical examples include recording data on requests and responses, processing security protocols, management session properties, and more. The filter provides an object-oriented modular mechanism for encapsulating a common task into an insertable component, which is declared by a configuration file and dynamically processed.

Many elements in the servlet filter are combined such that the filter is a unique, powerful and modular web component. In other words, the servlet filter is:

Declared: Filter declares through the XML tag in the Web Deployment Descriptor (Web.xml). This allows the filters to be added and deleted without having to change any application code or JSP page. Dynamic: The filter is called to intercept and process requests and responses by servlet container at runtime. Flexible: Filters are widely used in web processing environments, covering many of the most public auxiliary tasks such as logging and security. Filters are still flexible because they can be used to perform prerequisites and postparts for direct calls from the client, and processes requests between WEB components after the firewall. Finally, the filter can be linked to provide the necessary functions. Modular: By encapsulating the application processing logic into a single class file, the filter defines a modular unit that can easily add or delete from the request / response chain. Portable: Like many of the other aspects of the Java platform, servlet filters are transplantable across platforms and across containers, further supporting the modularity and reusable nature of the Servler filter. Reusable: Attributed a modular design of the filter to realize the class, as well as the declarative filter configuration, the filter can easily use different items and applications. Transparent: In the request / response chain, the filter includes a filter for supplementation (instead of replacing) the core processes provided by the servlet or JSP page. Thus, the filter can be added or deleted as needed without damaging the Servlet or JSP page.

So the servlet filter is a modular reusable component that flexibly declared through a configuration file. The filter dynamically handles the incoming request and the response, and does not need to modify the application code to be transparently added or deleted. Finally, the filter is independent of any platform or servlet container, allowing them to be easily deployed into any compatible J2EE environment. In the next few 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 explore some practical applications of the Servlet filter, and finally review the model-View-Controller (MVC) architecture containing the servlet filter to end the discussion herein.

The servlet filter architecture is as indicated by its name, the servlet filter is used to intercept the incoming request and / or the response, and monitor, modify, or handle the data stream being passed in some way. The filter is self-contained, modular components, which can be added to the request / response chain, or delete them without affecting other web components in the application. Filters are just a modified request and response runtime processing, so it should not be embedded directly into the web application framework unless it is implemented by a good defined standard interface through the servlet API.

The web resource can be configured to associate with the filter (this is the default), associated with a single filter (this is typical), even associated with one filter chain. So what is 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 to the client directly. If the request is forwarded, it will be passed to the next resource in the chain (another filter, servlet, or JSP page). After this request is managed by the filter chain and is processed by the server, a response will be sent back through the chain in the opposite order. This gives each filter provide an opportunity to process the response object as needed.

When the filter is first introduced in the Servlet 2.3 specification, they can only filter content between the designated Web resources accessed by the web client and the client. If the resource is then scheduled to other Web resources, the filter cannot be applied to any request to be delegated. 2.4 The specification eliminates this limit. The Servlet filter can now be applied to anywhere in the J2EE web environment existing requests and responding objects. Therefore, the servlet filter can be applied between clients and servlets, between servlet, and servlets, or JSP pages, and between each JSP page included. This is the power and flexibility I call!

Implement a servlet filter they say "good things". I don't know who "they" refers to, or this ancient proveric has more realities, but it is true that a servlet filter has to experience three steps. First, write the filter to implement the class, then add the filter to the web application (declare it in the Web Deploy Descriptor / Web.xml), finally package the filter and deploy the filter with the application. it. We will study each step in this detail.

1. Write the program filter API contains 3 simple interfaces (also numbers 3!), Which neatly nested in the Javax.Servlet package. The three interfaces are Filter, Filterchain and FilterConfig. From a programming perspective, the filter class will implement the Filter interface and then use the filterchain and the filterconfig interface in this filter class. A reference to the filter class will be passed to the Filterchain object to allow the filter to pass control to the next resource in the chain. The FilterConfig object will be supplied by the container to the filter to allow initialization data of the filter. In order to be consistent with our three-step mode, the filter must use three methods to fully implement the FILTER interface:

INIT (): This method is called when the container instantiates the filter, which is mainly designed to prepare the filter for processing. This method accepts an object of a FilterConfig type as an input. DOFILTER (): With a service () method with servlet (this method is called dopost () or doget ()) to handle the request, the filter has a single method for handling requests and responses - Dofilter (). This method accepts three input parameters: a servletRequest, Response, and a Filterchain object. DESTROY (): As you want, this method performs any cleaning operations, which may need to do before auto garbage collection.

Listing 1 shows a very simple filter that tracks the approximate time spending the web request to meet a client.

Listing 1. A filter class implementation

Import javax.servlet. *;

Import java.util. *;

Import java.io. *;

Public Class Timetrackfilter Implements Filter {

Private filterconfig filterfig = 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 of THE NEXT RESOURCE

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 ());

}

}

This filter's life cycle is very simple, no matter what, we still study it:

initialization

When the container loads the filter for the first time,

The init () method will be called. This class contains a pointing in this method.

The reference to the FilterConfig object. Our filters don't actually do this because there is no initialization information, which is just the purpose of the presentation.

filter

Most of the filters are consumed here.

The DOFILTER () method is called by the container, and it is incorporated into this request / response chain.

ServletRequest,

ServletResponse and

A reference to the Filterchain object. The filter then has the opportunity to handle the request, pass the processing task to the next resource in the chain (by call

FilterChain object reference

The DOFILTER () method) then processes the response when processing control returns the filter.

destruct

The container is adjusted before the garbage collection

Destroy () method to enable any required cleanup code.

2. Configure the servlet filter filter to declare the two XML tags in the web.xml file. Tag defines the name of the filter and declares the implementation class and init () parameters. The tab associates the filter with the servlet or URL mode.

Listing 2 From a web.xml file, it shows how to declare the included relationship of the filter:

Listing 2. Declare a filter in Web.xml

Page Request Timer

Timetrackfilter

Page Request Timer

main servlet

main servlet

mainservlet

main servlet / *

The above code example declares a filter ("Page Request Timer") and maps it to a servlet ("Main servlet"). A mapping is then defined for the servlet to send each request (specified by wildcards) to the servlet. This is a typical mapping declaration of the controller assembly. You should pay attention to the order of these claims, because never departure from the order of these elements.

3. Deploy a servlet filter In fact, deploy filters with a web application absolutely do not involve any complexity. Just put the filter class and other web components classes together, and put the web.xml file (along with the filter definition and filter mapping declaration) as you usually make in the web application structure, the servlet container will Other things after processing.

Many of the filters You use the filter's ability to use the filter in the J2EE Web application, just subject to your own creativity and application design skills. You can use a filter anywhere in the use of decorative filter modes or interceptor modes. Some of the most common applications of filters are as follows:

Loading: For all requests to reach the system, the filter collects information such as browser types, time, forwarding URL, etc., and conducts logging. Performance: The filter is transmitted through the line and extracts the content before reaching the servlet and the JSP page, and then the response content is obtained, and convert it to a compressed format before sending the response content to the client machine. Safety: Filter handles authentication tokens management, and appropriately limits access to security resources, prompting users to authenticate and / or guide them to third parties for authentication. Filters can manage access control lists (Accept Control List, ACL) to provide authorization mechanisms in addition to authentication. Place security logic in the filter instead of being placed in a servlet or JSP page, this provides huge flexibility. During development, the filter can be turned off (comment in the web.xml file). In production applications, the filter can be enabled again. Also add a plurality of filters to improve the level of security, encryption, and unrebeiled services as needed. Session Processing: Mixing Servlet and JSP pages with session processing code may bring considerable trouble. Use a filter to manage sessions allow web pages to concentrate on considering content display and delegate processing without having to worry about the details of session management. XSLT conversion: No matter how XML-based Web services use mobile clients, it is absolutely noble in implementing logical embedded applications on XML syntax.

Make the filter to adapt to the MVC architecture model - View-Controller (MVC) architecture is an effective design, which has now been used as the most important design methodology, integrated into large, such as Jakarta Struts and Turbine. Most popular Web application frameworks. The filter is intended to expand the request / response process of the MVC architecture. Regardless of whether the request / response occurs between the client and the server, the filter is the same in the processing stream between the other components of the server. From the viewpoint of MVC, the scheduler assembly (which is included in the controller assembly, or the controller component works) forwards the request to the appropriate application component for processing. This causes the controller layer to become the best location including a servlet filter. By placing the filter front 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 a separate web component. The MVC architecture is widely propagated and has a good document. Please understand more information about servlet implementations in the MVC and MVC architecture via the links in the reference.

Although the filter has occurred for a few years, they have been embedded in all agile, object-oriented J2EE web applications as a key component. This article introduces you to the use of servlet filters. This article discusses the advanced design of the filter, compares the current specification (2.4) and previous (2.3) models, telling the accurate steps involved in implementing the filter, and how to declare the filter in the web application, then with the application Deploy it together. This article also expounds some of the most common applications of the servlet filter and refers to how the filter adapts to the traditional MVC architecture.

This is the last article of the J2EE explorer series. We started our journey through a rough study at the beginning of the ENTERPRISE JAVABEAN assembly and mentioned when used to use these components. And when these components would become small. Then we turn your gaze to the web layer, draw a path to countless selection and functionality in the Servlet, JSP page, JavaBean technology, and Java Servlet API. In this series of articles, it is a happy thing with you with you. I have fun to write this series of articles, and I know from everyone's feedback, this is also a very valuable process for you. Thank you for your participation of this series. I wish you good luck and explore happiness!

Reference

转载请注明原文地址:https://www.9cbs.com/read-84989.html

New Post(0)