Javaweb filter--Filter Introduction

Source: Internet
Author: User

This article was reproduced from: http://blog.csdn.net/wanghuan203/article/details/7325651

A filter is a middleware that acts as a filter between the source data and the destination data.

In Web applications, when processing requests, there are often common tasks, such as setting the character set. This kind of work needs to be written on every page, which is laborious and difficult to modify.

Using filters is like adding a block to these processes, putting the required actions into a block, and all the processes that pass through the block are "executed".

Developing a filter must implement a Java-defined Javax.servlet.Filter interface:

This interface contains the methods that three filters must perform:

    • doFilter(ServletRequest, ServletResponse, FilterChain): This is a way to complete the filtering behavior. This is also the method called by the upstream filter. The introduced FilterChain object provides the information to be called by subsequent filters. If the filter is the last filter in the filter chain, the request is handed to the requested resource. You can also return the response information directly to the client.
    • init(FilterConfig) : called by the Web container to complete the initialization of the filter. It is guaranteed to be doFilter() called by the container before the first call. You can obtain the initialization parameters specified in the Web. xml file.
    • destroy() : called by the Web container to release the resource, doFilter() after all activities in it have been terminated by that instance.

Code Demo

public  class  testfilter  Filter {public  void  init (filterconfig arg0) throws   Servletexception {}  public  void   Destroy () {}  public  void   DoFilter (ServletRequest request, servletresponse response, Filterchain chain) throws   IOException, servletexception {}} 

After the filter development is completed, it needs to be configured in Web. Xml.

Code Demo: Adding a filter configuration to Web. xml

<Filter>          <Filter-name>Testfilter</Filter-name>        <Filter-class>Com.wh.filter.TestFilter</Filter-class>       <Init-param>               <Param-name>Characterencoding</Param-name>             <Param-value>UTF-8</Param-value>        </Init-param> </Filter>  <filter-mapping>        <Filter-name>Testfilter</Filter-name>       <Url-pattern>/*</Url-pattern></filter-mapping>

Analytical:

The <filter> node describes which class the filter corresponds to. Indicate the specific path

<filter-name> in <filter-mapping> must be the same as the <filter-name> value in the <filter> node.

<init-param> is the filter parameter. This parameter is obtained in the following way:

public void init (Filterconfig filterconfig) throws Servletexception {

characterencoding = Filterconfig.getinitparameter ("characterencoding");

}

<url-pattern> Specifies the URL style to be associated with the filter.

Url-pattern There are four main ways of matching

(a) Exact match, which is to fill in the specific address of a request to be filtered, such as Jap or servlet, for example:/filter/testfilter

(b) Extended match, consisting of "*" and extension, e.g. *.jsp

(c) Path prefix matching, containing a directory and a/* For example:/servlet/* refers to filtering all resources under the Servlet directory

(d) All matches, using/*, refers to the right so resources are filtered

The filter process is described in general:

When a request is initiated, the Web container first determines whether there is a filter and the resource associated with the request, and if there is an association, the request is given to the filter to be processed, the content of the request can be changed in the filter, and then the request is forwarded to the requested resource. When the requested resource responds, the Web container also forwards the response to the filter, where the response can be processed and the response sent to the client. In this whole process the client and target resources are unaware of the existence of the filter.

The filter makes two requests (request and response) filtering, in fact, the filter is the request and response to intercept. Intercepted and processed, and then returned to its original invocation process. This reflects the chain of responsibility model.

Multiple filters can be configured in a Web application to form a filter chain.

When a resource is requested, the filter in the filter chain processes the request in turn. The response is processed in the reverse order when the response is received.

The order in which multiple filters are executed is determined by the upper and lower order of the filter configuration in Web. Xml.

Benefits of using filter:

The client and target resources do not know the existence of a filter during the entire process of filter execution. Filter provides a declarative service, that is, if you do not have to make any changes to the original program, just write filter, the original program to use the filter, only need to declare in the XML file. He has the ability to plug and match with the web. XML, when not needed, only need to modify the Web. XML, no impact on the entire system, this declarative service is very convenient and very powerful.

Second, the use of filter to control the business is also very convenient, such as verifying whether the user is logged in, whether there are operational permissions, judgment session, character set, etc., put in the filter, you can save a lot of repetitive code and cumbersome control.

Where to apply filters commonly found in web development:

1, the user request for unified authentication, rights Management

2, the user's access request to record and audit

3, filter and replace the data sent by the user

4. Convert Image format

5, compress the content of the response, reduce the amount of transmission

6, the request and the corresponding encryption processing

Finally, it is important to note that the filter technique only works on post requests .

Javaweb filter--Filter Introduction

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.