JAVA Learning -- Filter explanation for JAVA Web

Source: Internet
Author: User


In the DRP project, we mentioned Filter multiple times, which solves the unified settings of character sets and unified control of simple WebCache. From this, we can understand that, it not only reduces the amount of code, but also avoids repeated coding on each page and reduces our workload, in addition, it brings great convenience to maintenance. How can it achieve unified management? Since it can manage repeated operations in a unified manner, what is the relationship between it and AOP?

 

Introduction to Filter

 

ServletAPI provides a Filter interface. When developing a web application, if the written Java class implements this interface, this java class is called a Filter.

With the Filter technology, developers can intercept access requests and responses before accessing a target resource. Simply put, a web Container can process the interception of a resource before its access, and intercept a resource before it returns a response to the web container.

 

Is the UML diagram of the filter call relationship:



A filter must implement javax. servlet. Filter.

Three methods

1. voidsetFilterConfig (FilterConfig config) // sets the configuration object of the filter;

2. FilterConfiggetFilterConfig () // return the configuration object of the filter;

3. voiddoFilter (ServletRequest req, ServletResponse res, FilterChain chain) // execute filter

 

How filters intercept

 

The Filter interface has a doFilter method. After developers compile the Filter class to implement the doFilter method and configure which web resource to intercept, each time a WEB server calls the service method of a web Resource (determined by the internal resource access mechanism of the server), it will first call the doFilter method of filter.

 

Example:

 

Batch Set Request Encoding


Public class EncodingFilter implements Filter {private String encoding = null; public void destroy () {encoding = null;} public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, servletException {String encoding = getEncoding (); if (encoding = null) {encoding = "gb2312";} request. setCharacterEncoding (encoding); // specify the encoding chain in the request. doFilter (request, response); // by controlling the chain. doFilter method call to determine whether to access the target resource} public void init (FilterConfig filterConfig) throws ServletException {this. encoding = filterConfig. getInitParameter ("encoding");} private String getEncoding () {return this. encoding ;}}

Xml configuration code


<filter>      <filter-name>EncodingFilter</filter-name>      <filter-class>com.logcd.filter.EncodingFilter</filter-class>      <init-param>         <param-name>encoding</param-name>         <param-value>gb2312</param-value>      </init-param>  </filter>    <filter-mapping>     <filter-name>EncodingFilter</filter-name>     <url-pattern>/*</url-pattern>  </filter-mapping>  

The function completed by the code above is that no matter which page you enter, you must first execute the dofilter method of the EncodingFilter class to set the character set.

 

The doFilter () method is similar to the service () method of the Servlet interface. When the client requests the target resource, the container will call the doFilter () method of the filter associated with the target resource.

The request and response parameters are the requests and corresponding objects passed by the previous Filter of the web Container or Filter chain. The chain parameter represents the objects of the Current Filter chain.

 

The FilterChain interface represents the object of the Current Filter chain. Implemented by the container. The container uses its instance as a parameter to pass in the doFilter () method of the filter object.

The filter object uses the FilterChain object to call the next filter in the filter chain, or the target Servlet program to process it, you can also directly return the response information to the client, or use the forward () and include () of RequestDispatcher () and the sendRedirect () method of HttpServletResponse redirects requests to other resources.

The request and Response parameters of this method are ServletRequest and ServletResponse. That is to say, the use of filters does not depend on specific protocols.

 

Filter Lifecycle

 

Like Servlet, the WEB server is responsible for Filter creation and destruction.


What's different from Servlet is:


1> when the application is started, the Filter class is loaded, while the servlet is created only at the request time (but the load-on-startup configuration of the filter and Servlet is the same ).

2> call the init () method after the Filter object instance is created in the container. Then the Web container is saved to the application-level collection container, waiting for the user to access the resource.

3> when the user's accessed resources are intercepted by the Filter url-pattern, the container will retrieve the Filter class and call the doFilter method. When the user accesses the intercepted resources for the next or multiple times, the Web Container directly extracts the specified Filter object instance and calls the doFilter method (the Filter object is resident in the Web container ).

4> when the application service is stopped or reloaded, the destroy method of Filter is executed and the Filter object is destroyed.

 

Filter working principle (Execution Process)

When the client sends a request for Web resources, the Web server checks based on the filtering rules set in the application configuration file. If the customer request meets the filtering rules, the client requests/responses are intercepted, check or modify request headers and data, use the filter chain in sequence, and finally send the request/response to the requested Web resource for processing.

The request information can be modified in the filter chain, or the request cannot be sent to the resource processor based on the condition, and a response can be sent directly to the client. After the resource processor completes processing the resource, the response information is returned in reverse order. In this process, you can modify the response information to complete certain tasks.

The advantage of the filter chain is that the chain can be interrupted at any time during execution. As long as the chain. doFilter () is not executed, the following filters and request content will no longer be executed.



ForMultiple FiltersFor example, EncodingFilter is responsible for encoding, SecurityFilter is responsible for controlling permissions, and the server will follow the web. the filters defined in xml are sequentially assembled into a chain, and then the doFilter () method is executed at one time. In actual use, pay special attention to the execution sequence of the filter chain, for example, EncodingFilter must be placed before all filters, so as to ensure correct encoding before using the data in the request.

 

Summary:

 

I believe everyone understands the filter application. Its main function is to intercept and process the access requests and responses before users access a target resource, then the target program is called. The advantage of this is that some common operations can be abstracted. If this method is not used, set the character set, we need to write a character set statement on each page. It is not only troublesome but difficult to maintain, but if you use filter, you only need to add a class and configure it in xml. If you do not want to use it, remove the content in the configuration file.

 

In fact, this is a kind of AOP (Aspect OrientedProgramming) for Aspect-Oriented Programming. Its main intention is to divide the log records, Performance Statistics, security control, transaction processing, Exception Processing and other codes from the business logic code. By separating these behaviors, we hope that they can be independent into non-guided business logic methods, and thus change these behaviors without affecting the business logic code.

For the set character set, it is not the content of the business logic. We can extract the content for processing and use the filter for overall settings, this method is equivalent to further abstracting the content in the class, making our system more flexible and able to cope with changes!

 

Q:

 

Since the dynamic proxy introduced in the previous blog is a manifestation that conforms to AOP, And now we also say that Filter is also in line with AOP, you will have a question, what is the difference between dynamic proxy and Filter processing? Since First is consistent with the idea of AOP, it must be able to perform unified processing (in fact, the core is to further abstract ). What is the difference?

 

In terms of performance, the two are indeed very similar. You can also add other actions before and after the jsp and servlet code you write, but the two are essentially different.

1. The filter is based on the callback function. The doFilter method in the filter interface we need to implement is the callback function, while the dynamic proxy is based on the reflection mechanism of java itself. If you do not understand this form, you can look at the dynamic proxy implementation process, which is the basis of aop. This is the essential difference between the two.

2. filter depends on the servlet container, that is, it can only be executed in the servlet container. Obviously, the doFilter method cannot be called back and forth without the servlet container. Dynamic proxy has nothing to do with servlet containers.






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.