Java Filter (Interceptor)

Source: Internet
Author: User

Multiple filter executions are performed according to the filter order configured in the configuration file.

Configuring the filter in the Web. xml file, using the Init-param element to configure the parameter for the filter, Init-param accepts the following two child elements:

Param-name: Specifies the name of the parameter.

Param-value: Specifies the parameter value.

Filter, filter-mapping, servlet, servlet-mapping constitute a complete interceptor configuration.

The filter class needs to implement the filter interface, which has init, DoFilter, and Destroy3 methods, and 3 methods are executed sequentially.

Filter, also known as filters, is a more exciting technology in Servlet technology, Web developers through the filter technology, Web server management of all Web resources: such as JSP, Servlet, static picture files or static HTML files, etc. to intercept, So that some special functions can be realized. For example, the implementation of URL-level access control, filtering sensitive words, compressed response information and other advanced features.


Second, Filter introduction
The Servlet API provides a filter interface that, when developing a Web application, if the Java class is written to implement this interface, the Java class is called filter filter. Filter technology enables developers to intercept requests and responses to access before they access a target resource. Simply put, it is possible to implement a Web container for the pre-access interception of a resource before processing it, or to intercept a resource before it returns a response to the Web container.
Iii. Quick Start
1. Create a new class to implement the filter interface
2, implement the Dofilter () method, print a word, to prove the ability to intercept
3. Configuring in Web. XML (refer to servlet configuration)
4. Visit a page to see if you can intercept
1>
[Java] View plaincopy
Package com.test.filter;

Import java.io.IOException;
Import Javax.servlet.Filter;
Import Javax.servlet.FilterChain;
Import Javax.servlet.FilterConfig;
Import javax.servlet.ServletException;
Import Javax.servlet.ServletRequest;
Import Javax.servlet.ServletResponse;
public class Demo1filter implements Filter {
Private Filterconfig Filterconfig;

public void DoFilter (ServletRequest request, servletresponse response,
Filterchain chain) throws IOException, Servletexception {
System.out.println ("Demo1 filter Before");
System.out.println (Filterconfig.getinitparameter ("param1"));
Chain.dofilter (request, response);//release. Let it go to the next chain or target resource
System.out.println ("Demo1 after filtration");
}

public void init (Filterconfig filterconfig) throws Servletexception {
System.out.println ("initialized");
This.filterconfig = Filterconfig;
}

public void Destroy () {
System.out.println ("destroyed");
}
}
2> configuration in Web. xml
[HTML] View plaincopy
<filter>
<filter-name>Demo1Filter</filter-name>
<filter-class>com.itheima.filter.Demo1Filter</filter-class>
<init-param>
<param-name>param1</param-name>
<param-value>value's here. </param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Demo1Filter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher> <!--Not Configured dispatcher is the default REQUEST method--
<dispatcher>FORWARD</dispatcher>
<dispatcher>ERROR</dispatcher>
<dispatcher>INCLUDE</dispatcher>
</filter-mapping>

Iv. Application Scenarios for filter
By understanding filter filter, you can know that in the following three situations can do some processing:
1> determines whether the target resource needs to be accessed by controlling the invocation of the Chain.dofilter method.
For example, user permissions can be verified and so on. Determine whether the user has access to certain resources, have permission to release, do not have permission to execute the Chain.dofilter method.
2> to achieve some purpose by doing some processing before calling the Chain.dofilter method.
For example, solve the problem of Chinese garbled and so on. The encoding of the request encoding and response can be performed before the Dofilter method. The request interface can even be encapsulated to handle the Chinese garbled problem of Get requests (overriding the corresponding Request.getparameter method).
3> does this by doing some processing after invoking the Chain.dofilter method to achieve some purpose.
For example, the entire Web site compression. Use Class A to encapsulate the response object before calling the Chain.dofilter method, overriding the Getoutputstream and overriding the Getwriter method. Within Class A, the output is cached into the Bytearrayoutputstream stream. Then after the Chain.dofilter method executes, gets the Bytearrayoutputstream stream cache data in Class A, compressed with the Gzipoutputstream stream.
Five, filter to achieve the principle of interception
The filter interface has a Dofilter method that, when the developer writes the filter class to implement the Dofilter method, and configures which web resource to intercept, the Web server each time before invoking the service method of the Web resource ( The server's internal access to the resource) will call the Dofilter method of the filter first.
Vi. Filter Life cycle
As with Servlets, the creation and destruction of the filter is also the responsibility of the Web server. However, unlike the servlet, it is 1> loading the filter class (the same as the servlet's load-on-startup configuration) when the application is started. After the 2> container has created the Filter object instance, call the Init () method. The Web container is then saved into the application-level collection container and waits for the user to access the resource. 3> when a user accesses a resource that is intercepted by the url-pattern of the filter, the container takes out the filter class and calls the Dofilter method, and the next or multiple access to the intercepted resource The Web container takes the specified Filter object instance directly out of the call Dofilter method (the filter object resides in the Web container). 4> when the application service is stopped or reloaded, the filter's Destroy method is executed and the filter object is destroyed.
Note: The Init method and the Destroy method will only be used directly once.
VII. Filter Deployment Application Considerations
1> filter-mapping tags in servlet-name and url-pattern.
Filter can not only specify which URL-matching resources are blocked by Url-pattern. The servlet-name can also be used to specify which servlet to intercept (specifically for a servlet service, servlet-name corresponding to the servlet's configuration).
2> filter-mapping tag in dispatcher.
Specifies how the resource that the filter intercepts is called by the Servlet container, which can be one of Request,include,forward and error, the default request. Users can set multiple <dispatcher> child elements to specify the Filter to intercept multiple calls to the resource.
REQUEST:
When a user accesses a page directly, the Web container invokes the filter. The filter is not invoked if the target resource is accessed through the RequestDispatcher's include () or forward () method or the error condition.
INCLUDE:
If the target resource is accessed through the include () method of RequestDispatcher, then the filter is called. In addition, the filter is not called.
FORWARD:
If the target resource is accessed through the RequestDispatcher forward () method, the filter will be called, except that the filter will not be called.
ERROR:
If the error attribute =examerror.jsp is specified in the page directive of the a.jsp, then if an exception occurs in the a.jsp, it jumps to the examerror.jsp processing. When jumping to examerror.jsp, if the filter is configured with the error dispather then it will intercept, otherwise it will not intercept.

Turn, has been repeatedly turned, can not find the original source.

Java Filter (Interceptor)

Related Article

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.