11_java_cao jianbo 12.03 Servlet Filter (Filter)

Source: Internet
Author: User

Servlet Filter)

Introduction to Filter

Filter is also called a Filter. It is the most exciting technology in Servlet technology. WEB developers use the Filter technology to manage all web resources on web servers, such as Jsp, Servlet, static image files or static html files are intercepted to implement some special functions. For example, some advanced functions such as URL-level access control, filtering sensitive words, and compressing response information are implemented. Www.2cto.com

The Servlet API provides a Filter interface. When developing a web application, if the written Java class implements this interface, the java class is called a Filter. With the Filter technology, developers can intercept access requests and responses before accessing a target resource, as shown below:

How does Filter implement interception?

The Filter interface has a doFilter method. After developers compile the Filter and configure which web resource to intercept, the WEB server calls the service method of the web Resource each time, the doFilter method of filter is called first. Therefore, you can write code in this method to achieve the following purpose:

Run a piece of code before calling the target resource.

Whether to call the target resource (that is, whether to allow users to access web resources ).

When the web server calls the doFilter method, it will pass in a filterChain object. The filterChain object is the most important object in the filter interface. It also provides a doFilter method, developers can determine whether to call this method as needed. When this method is called, the web server will call the service method of the web resource, that is, the web resource will be accessed, otherwise, the web resources will not be accessed.

After calling the target resource, let a piece of code be executed

Experiment: Filter development. For more information, see the development process in the next PPT.

Getting started with Filter development

Filter development involves two steps:

Compile the java class to implement the Filter interface and implement its doFilter method.

Use the <filter> and <filter-mapping> elements in the web. xml file to register the written filter class and set the resources it can block. (Hands-on Lab)

Filter chain

In a web application, you can develop and compile multiple filters. These filters are called a Filter chain in combination.

The web server depends on the Filter in the web. the registration order in the xml file determines which Filter to call first. When the doFilter method of the first Filter is called, the web server creates a FilterChain object representing the Filter chain and passes it to the method. In the doFilter method, if the developer calls the doFilter method of the FilterChain object, the web server will check whether there is a filter in the FilterChain object. If there is a filter, the web server will call 2nd filters. If not, then the target resource is called.

Filter chain Experiment (view filterChain API Documentation)

Servlet Filter

It should be noted that the Filter is not a Servlet and cannot generate a response. It can pre-process the request before a request arrives at the Servlet, or it can process the response when it leaves the Servlet.

Combine multiple filters into a filter chain, and each filter executes a task in the application, which helps ensure their adequacy and reusability.

When the Web Container receives a request, multiple operations will occur:

The Web Container performs preprocessing on the request. The container vendor is responsible for what happens in this step.

The Web container checks whether a filter matches the URL pattern of the requested URL.

The Web Container uses a matching URL mode to locate the first filter. Execute the code for this filter.

If there are other filters with matching URL patterns, execute the code to continue the process until there are no other filters with matching URL patterns.

If no error occurs, the request is passed to the target Servlet.

The Servlet returns the response to its caller. The last Filter Applied to the request is the first filter applied to the response.

The first filter originally applied to the request passes the response to the Web container.

Public void doFilter (ServletRequest req, ServletResponse res, FilterChain chain) is the core method in the Filter.

The FilterChain object is the object that stores the execution sequence of multiple filters.

Lifecycle of a Filter

Init (FilterConfig filterConfig) throws ServletException:

Like our Servlet program, the WEB server is responsible for the creation and destruction of filters. When a web application is started, the web server will create a Filter instance object and call its init method to complete object initialization, so as to prepare for the interception of subsequent user requests (Note: The filter object will be created only once, and the init method will be executed only once. Example)

By using the parameters of the init method, developers can obtain the FilterConfig object that represents the current filter configuration information. (For the filterConfig object, see the PPT on the next page)

Destroy ():

Called before the Web Container unmounts the Filter object. This method is only executed once in the lifecycle of the Filter. In this method, resources used by the filter can be released.

FilterConfig Interface

When configuring the filter, you can use <init-param> to configure some initialization parameters for the filter. When the web Container instantiates the Filter object and calls its init method, the filterConfig object that encapsulates the filter initialization parameters is passed in. Therefore, when writing a filter, developers can use the filterConfig object method to obtain:

String getFilterName (): Get the filter Name.

String getInitParameter (String name): return the value of the initialization parameter specified in the deployment description. If no data exists, null is returned.

Enumeration getInitParameterNames (): returns an Enumeration set of the names of all initialization parameters of the filter.

Public ServletContext getServletContext (): return the reference of the Servlet context object.

Experiment: Get the filter configuration information

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.