Detailed introduction and example code of Java filter
Introduction to filter
Filter, also known as filter, is the most practical technology in Servlet Technology. Web developers use filter technology to intercept all web resources managed by web server, such as JSP, servlet, static picture file or static HTML file, so as to realize some special functions. For example, it implements some advanced functions such as URL level permission access control, filtering sensitive words, compressing response information and so on.
It is mainly used to preprocess user requests or post process httpservletresponse. The complete process of using filter: filter preprocesses the user request, then sends the request to the servlet for processing and generates a response, and finally filter post processes the server response.
Filter function
1. Intercept the customer's HttpServletRequest before the HttpServletRequest arrives at the servlet. Check the HttpServletRequest as needed, or modify the HttpServletRequest header and data.
2. Intercept the httpservletresponse before the httpservletresponse reaches the client. Check the httpservletresponse as needed, or modify the httpservletresponse header and data.
How to implement interception function with filter
There is a dofilter method in the filter interface. After the developer writes the filter and configures which web resource to intercept, the web server will call the dofilter method of the filter every time before calling the service method of the web resource. Therefore, writing code in this method can achieve the following purposes:
1. Let a piece of code execute before calling the target resource.
2. Whether to call the target resource (i.e. whether to let the user access the web resource).
When calling the dofilter method, the web server 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 decide whether to call this method according to their needs. If they call this method, the web server will call the service method of web resources, that is, the web resources will be accessed, Otherwise, the web resource will not be accessed.
Two steps for filter development
Write a Java class to implement the filter interface and implement its dofilter method. On the web The and elements are used in the XML file to register the written filter class and set the resources it can intercept. web. Introduction to XML configuration nodes:
The < filter mapping > element is used to set the resources intercepted by a filter. The resources intercepted by a filter can be specified in two ways: servlet name and resource access request path
< servlet name > specifies the name of the servlet intercepted by the filter.
< dispatcher > specifies how the resource intercepted by the filter is called by the servlet container. It can be one of request, include, forward and error. The default is request. The user can set multiple < dispatcher > sub elements to specify the filter to intercept multiple calls to resources.
Values that can be set by < dispatcher > child elements and their meanings
Filter chain
In a web application, you can develop and write multiple filters, which are combined to be called a filter chain.
The web server is on the web according to the filter 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 will create a filterchain object representing the filter chain and pass 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 so, the second filter will be called. If not, the target resource will be called.
Filter lifecycle
Like the servlet program we write, the web server is responsible for the creation and destruction of filter. When the web application starts, the web server will create an instance object of filter and call its init method to read the web XML configuration to complete the initialization function of the object, so as to prepare for interception of subsequent user requests (the filter object will be created only once, and the init method will be executed only once). Developers can obtain the filterconfig object representing the current filter configuration information through the parameters of the init method.
This method completes the actual filtering operation. When a client requests access to the URL associated with the filter, the servlet filter will first execute the dofilter method. The filterchain parameter is used to access subsequent filters.
After the filter object is created, it will reside in memory and will not be destroyed until the web application is removed or the server is stopped. Called before the web container unloads the filter object. This method is executed only once in the life cycle of the filter. In this method, the resources used by the filter can be released.
Filterconfig interface
When configuring the filter, users can configure some initialization parameters for the filter. When the web container instantiates the filter object and calls its init method, it will pass in the filterconfig object that encapsulates the filter initialization parameters. Therefore, when writing filter, developers can obtain the following contents through the method of filterconfig object:
Filter use case
Use filter to verify user login security control
Some time ago, I participated in the maintenance of a project. After exiting the system, the user can access the history in the address bar. According to the URL, he can still enter the system response page. I went to check and found that the request was not filtered to verify the user login. Add a filter to solve the problem!
First on the web XML configuration
Then write filterservlet java:
In this way, all requests to users can be completed, and the user login must be verified through this filter.
Anti Chinese garbled filter
When the project uses the spring framework. When the current JSP page and Java code use different character sets for coding, there will be the problem of garbled data submitted by the form or uploading / downloading Chinese name files. You can use this filter.
The opensessioninview filter of Spring + Hibernate controls the session switch
When hibernate + spring is used together, If lazy = true (delayed loading) is set, hibernate will automatically close the session after reading the parent data when reading the data. In this way, the system will throw lazyinit error when using the associated data and child data. In this case, it is necessary to use the opensessioninview filter provided by spring.
Opensessioninview filter is mainly used to keep the session state until the request sends all pages to the client, and close the session until the request ends. This can solve the problem caused by delayed loading.
Note: the opensessioninview filter configuration should be written in front of the Struts2 configuration. Because the Tomcat container loads the filters in order, if the configuration file first writes the filter configuration of struts 2, and then the filter configuration of opensessioninview filter, the loading order causes that the session is not managed by spring when the action obtains data.
Struts 2 web XML configuration
Using struts 2 in the project also needs to be on the web XML configuration filter is used to intercept requests and go to the action of struts 2 for processing.
Note: if in 2.1 3. In previous versions of struts 2, the filter uses org apache. struts2. dispatcher. FilterDispatcher。 Otherwise, use org apache. struts2. dispatcher. ng. filter. StrutsPrepareAndExecuteFilter。 From struts 2 Starting from 1.3, the actioncontextcleanup filter will be discarded, and the corresponding functions will be included in the struts prepareandexecutefilter filter.
Three initialization parameter configurations:
Thank you for reading, hope to help you, thank you for your support to this site!