My blog: http://wxmimperio.coding.io/
I e-mail: [Email protected]
first, the introduction of filters:
- A filter is defined in Servlet specification 2.3, which is a server-side component that intercepts the client's request and response information and filters the information.
- The servlet filter itself does not generate request and response objects, but only provides filtering functionality.
- The servlet filter can examine the request object before the servlet is invoked and modify the request header and request content.
- The Web components that the servlet filter can filter include files such as servlet,jsp and HTML.
This article source code--github:
Https://github.com/imperio-wxm/wordpressCode/tree/master/Filter
Second, the filter in the actual development of the application Scenario 1. Unified authentication for user requests 2. Encoding Conversion 3. Filtering and replacing the data sent by the user 4. Convert image format 5. Compress the corresponding content Third, the working principle of the filter
"No Filter":
Users access Web resources directly.
"With filter":
When the Web container starts, the filter is loaded, the user makes a request to the filter, the filter determines whether the request conforms to the rule, the request that conforms to the rule is sent through the filter to the Web resource, the Web resource response is returned to the filter, and the filter returns the response of the Web resource to the user.
Iv. the life cycle of the filter (similar to the life cycle of the servlet)
1. Instantiation-Configuration loading via web. XML, only once when the container is started
2. Initialize--Call the Init () method, loading information will only be executed once
3. Filtering-Multiple filtration using the Dofilter () method
4. Destroy--web container when closed call Destroy () method to destroy
All servlet filters must implement the Javax.servlet.Filter interface and implement the three methods in the interface.
"Init () method"
- This is the method of initialization of the filter, which is called when the Web container creates the filter instance. In this method, the parameters of the filter in the Web. xml file can be used.
"DoFilter () method"
- This method completes the actual filtering operation. This place is the core of the filter, and when the user requests access to the URL associated with the filter, the Web container will first call the filter's Dofilter method.
- The Filterchain method parameter can call the Chain.dofilter method, pass the request to the next filter (or target resource), or forward to another resource with a forward, redirect request.
"Destroy () method"
- The Web container calls this method before destroying the filter instance, in which the resource used by the filter can be freed.
"Life Cycle Code Demo"
Package Com.filter;import javax.servlet.*;import java.io.ioexception;/** * Created by Wxm-imperio */public class Firstfilter implements Filter { @Override public Void Destroy () { System.out.println ("Destroy, Firstfilter "); } @Override
Throws IOException, servletexception { System.out.println ("Start,dofilter,firstfilter"); Filterchain.dofilter (ServletRequest, servletresponse); System.out.println ("End,dofilter,firstfilter"); } @Override public void init (Filterconfig filterconfig) throws Servletexception { System.out.println ("Init. Firstfilter ");} }
"Web. XML Configuration"
<filter> <filter-name>filter's name </filter-name> name of <filter-class>filter class </ filter-class> <init-param> <description> Description information can be omitted or placed here </description> < param-name> parameter name </param-name> <param-value> value of parameter </param-value> </init-param> </filter><filter-mapping> <filter-name>filter's name </filter-name> <url-pattern >URL</url-pattern> <dispatcher></dispatcher>//Filter Type </filter-mapping>
Note: The generic filter is configured before all servlets.
Five, support multiple filters
- Each filter has a different URL address
- A filter chain is generated when the different filter URL addresses are the same:
- User requests--each filter in turn--web the resource (in order: The server consists of a chain in the order defined by the filter in Web. xml)
"User Request"-"filter 1chain.dofilter before code--Filter 1chain.dofilter--> filter 2chain.dofilter Front Code--Filter 1chain.dofilter ... "-" the Servlet service method handles the request "--> ..." filter 2chain.dofilter after the code--and filter 1chain.dofilter after code "-- "Return user Request"
"Web. Xml configuration for the filter chain"
<!--filter 1 configuration information--! ><filter> <filter-name>filter1 name </filter-name> <filter-class> The name of the Filter1 class </filter-class> <init-param> <description> description information can be omitted or placed here </description> < param-name> parameter name </param-name> <param-value> value of parameter </param-value> </init-param></filter ><filter-mapping> <filter-name>filter1 's name </filter-name> <url-pattern>url</ url-pattern> <dispatcher></dispatcher>//Filter Type </filter-mapping><!--Filter 2 configuration information--! >< Filter> <filter-name>filter2 's name </filter-name> <filter-class>filter2 class name </filter-class > <init-param> <description> Description information can be omitted or placed here </description> <param-name> parameter name </param -name> <param-value> values for parameters </param-value> </init-param></filter><filter-mapping> <filter-name>filter2 's name </filter-name><url-pattern>URL</url-pattern> <dispatcher></dispatcher>//Filter Type </filter-mapping>
Note: The order in which the filters are executed is the order in which they are configured in Web. Xml.
Vi. Classification of filters
Servlet2.5:
1.REQUEST (default) when a user accesses a page directly, the Web container invokes the filter. This filter is called when the 2.FORWORD target source is accessed through the RequestDispatcher ForWord method. The filter is called when the 3.INCLUDE target resource is called through the RequestDispatcher INCLUDE method. The filter is called when the 4.ERROR target resource is called through a declarative exception-handling mechanism. Syntax
@WebFilter (Servletnames = {"Simpleservlet"} filtername = "Simplefilter") public class Lessthansixfilter implements Filter {//Contents in class}
"Error configuration Information"
<error-page> <error-code>404</error-code> <location>/error.jsp</location ></error-page><filter> <filter-name>errorFilter</filter-name> < Filter-class>com.filter.errorfilter</filter-class></filter><filter-mapping> < Filter-name>errorfilter</filter-name> <url-pattern>/error.jsp</url-pattern></ Filter-mapping>
"Errorfilter Filter Code"
public class Errorfilter implements Filter { @Override public Void Destroy () { } @Override public void init (Filterconfig filterconfig) throws servletexception { } @Override
Throws IOException, servletexception { System.out.println ("error message detected");} }
Servlet3.0:
(new) Async supports asynchronous processing
- @WebFilter (Introduction) is used to declare one as a filter, which will be handled by the container at deployment time, and the container will be deployed as a filter based on the specific property configuration of the appropriate class.
"Asynchronous Operation processing code: Filters do not wait for threads, directly execute the following, implementing asynchronous Processing"
Asynservlet
Set the servlet to support asynchronous @webservlet (name = "Asynservlet", asyncsupported = true) public class Asynservlet extends HttpServlet {p rotected void DoPost (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {System.out.println ("servlet Execution start time" + New Date ()); Implement asynchronous operation Asynccontext context = Request.startasync (); Opens the async thread new Thread (new Executor (context)). Start (); System.out.println ("Servlet Execution End Time" + new Date ()); } protected void Doget (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {doPost (request, response); }//Internal class impersonation thread public class Executor implements Runnable {private Asynccontext context; Implement construction method Public Executor (Asynccontext context) {This.context = context; } @Override public void Run () {//execute related complex business try {thread.sleep (1000 * 1 0); Context.getrequest (); Context.getresponse (); SYSTEM.OUT.PRINTLN ("Business Execution Completion time" + new Date ()); } catch (Interruptedexception e) {e.printstacktrace (); } } }}
Asvnfilter Filter
"Asynfilter", value = {"/asynservlet"}, asyncsupported = True, Dispatchertypes = {dispatchertype.request, Dispatchertype.async}) public class Asynfilter implements Filter { @Override public Void Destroy () { } @Override public void init (Filterconfig filterconfig) throws servletexception { } @Override
Throws IOException, servletexception { System.out.println ("Start ..... Asynfilter "); Filterchain.dofilter (ServletRequest, servletresponse); System.out.println ("End .....") Asynfilter ");} }
Web. XML configuration
<servlet> <servlet-name>AsynServlet</servlet-name> <servlet-class> Com.servlet.asynservlet</servlet-class></servlet><servlet-mapping> <servlet-name> Asynservlet</servlet-name> <url-pattern>/asynservlet</url-pattern></servlet-mapping >
Vii. Use of Filterconfig
The Init method of filter provides a Filterconfig object that provides related operations:
For example, obtain the initialization parameters configured in Filter web. XML configuration:
<filter> <filter-name>LoginFilter</filter-name> <filter-class> com.itzhai.login.loginfilter</filter-class> <init-param> <param-name>username</ param-name> <param-value>arthinking</param-value> </init-param></filter>
In the Init () method, get:
@Overridepublic void init (Filterconfig filterconfig) throws Servletexception { //Get filter initialization parameter String Username = Filterconfig.getinitparameter ("username");}
Access the application in filter:
ServletContext context = Filterconfig.getservletcontext ();
It can also be obtained from the Dofilter method according to the converted request:
HttpServletRequest req = (httpservletrequest) request; ServletContext context = Req.getsession (). Getservletcontext ();
Viii. Examples of projects
MU class network user login to the enhanced version of the demo, the use of filters for requests and server response filtering.
GitHub Source: Https://github.com/imperio-wxm/projectDemo
Reference: JSP application Development Detailed (third edition), MU class net
Java Web Advanced--filter Filter