Do not trust the client, so do the back end of the people should remember things. Because the data from the front end is not always legal and effective, the backend is the last umbrella to access the resources. Before we talked about AOP programming, AOP Fundamentals in spring, it was possible to do some preprocessing and validation before executing our methods to protect the backend resources. It is not difficult to think of her implementation and this article to say the implementation of the filter should be the same principle, are implemented through the dynamic agent of Java (own understanding).
In the Java Web development, the filter is used to intercept the request , and the ServletRequest object is processed, we can think of, it can be used to verify the permissions, encryption and decryption, session inspection, data conversion, anti-theft chain and so on. As you can see, it is very important in Web application development.
One, the filter configuration uses 1, the configuration way filter's use has two kinds of configuration, and the servlet's use is similar, respectively uses the annotation and the deployment profile Web. Use the annotations to configure the filter as follows:
@WebFilter (filtername= "Myfilter", urlpatterns= "/myhttpservlet", initparams={@WebInitParam (name= "Server", value= " Www.baidu.com "), @WebInitParam (name=" Port ", value=" 443 ")}) public class Myservletfilter implements Filter {}
This is similar to a servlet, where the name of the filter, the URL of the app, is configured, and the URL here is the method of the filter class if the URL of the servlet matches the URL in this case if the client accesses the servlet. You can also configure initialization parameters. The Web. xml file is configured as follows:
<filter><filter-name>myServletFilter1</filter-name><filter-class> Com.javaservlet.servlet.filter.myservletfilter1</filter-class><init-param><param-name>server </param-name><param-value>www.baidu.com</param-value></init-param><init-param> <param-name>port</param-name><param-value>443</param-value></init-param></ filter><filter-mapping><filter-name>myservletfilter1</filter-name><url-pattern>/ Myhttpservlet</url-pattern></filter-mapping>
Note When you configure filter in a file, the configuration of the filter is placed before the servlet configuration. In the configuration of the properties there are other, you can refer to Javadoc to see.
2, the basic apifilter involves the following classes:
- Javax.servlet.Filter: Contains the life cycle method of the Filter, which is invoked when the servlet container is initialized or destroyed;
- Javax.servlet.FilterConfig: Contains configuration information about the filter, the most important of which is its initialization parameters;
- Javax.servlet.FilterChain: is provided by the servlet container to implement calls between multiple filters;
The Filte class is similar to a servlet, consisting of only three life cycle methods, so the call timing should be the same, call the Init () method when the container starts, and call the Destroy () method when the container is destroyed. The Dofilter () method is called when the resource associated with the filter is called. When the following container starts:
This procedure is followed by the listener of the Java Web basics: Monitor Each action of the servlet, so the program is the same, you can see the containerat startup, the servlet container initializes the listener by the listener, then initializes the filter, initializes the filter, initializes the servlet, and finally adds a property。 This is a complete boot process for the servlet container. When the container is destroyed, the following things happen:
The container destroys exactly when it is started with the opposite, destroys the servlet instance first, then destroys the filter, and finally the listener hears the container destroy and calls the relevant method. The most important thing in Filterconfig is to get the initialization parameters, which are similar to the servlet, as follows:
Filterconfig.getinitparameter ("server"); Enumeration<string> enums = Filterconfig.getinitparameternames (); while (Enums.hasmoreelements ()) {String ParamName = Enums.nextelement (); String paramvalue = Filterconfig.getinitparameter (paramname); System.out.println (paramname + "-" + Paramvalue);}
In addition, there are two methods in Filterconfig, of whichGetservletcontext () is more important, it can get a lot of information in ServletContext:
Filterconfig.getfiltername (); ServletContext context = Filterconfig.getservletcontext ();
Finally, the Filterchain class, the personal feeling that this is the most important class in the filter, only it is directly related to the resources that the user wants to access.
The DoFilter () method is where we implement specific interceptor logic, which modifies the content and properties of the request, or adds an HTTP header to the response, and then calls the Filterchain DoFilter () method after completing its own logic. The request instance and the response instance provided by the Servlet container are forwarded out, why do you need this method? Simply say a resource corresponding to the filter may be more than one, a filter will also intercept multiple requests, based on this mechanism, so a resource is actually a filter chain, each time a filter processing ends, the request is forwarded to other filters, until the last filter processing is completed, The request and response are sent to the corresponding servlet.
Note: Similar to servlet, the servlet container by default creates an instance for each filter class, which is also a single instance , and inevitably encounters a multi-threaded problem , so be aware of this.
The following is the complete filter instance:
@WebFilter (filtername= "Myfilter", urlpatterns= "/myhttpservlet", initparams={@WebInitParam (name= "Server", value= " Www.baidu.com "), @WebInitParam (name=" Port ", value=" 443 ")}) public class Myservletfilter implements Filter {public void Init (Filterconfig filterconfig) throws Servletexception {System.out.println ("Myservletfiler init"); Filterconfig.getinitparameter ("server"); Enumeration<string> enums = Filterconfig.getinitparameternames (); while (Enums.hasmoreelements ()) {String ParamName = Enums.nextelement (); String paramvalue = Filterconfig.getinitparameter (paramname); System.out.println (paramname + "-" + Paramvalue);} Filterconfig.getfiltername (); ServletContext context = Filterconfig.getservletcontext ();} public void DoFilter (ServletRequest request, servletresponse response, Filterchain chain) throws IOException, servletexception {System.out.println ("filter Service"); Chain.dofilter (request, response);} public void Destroy () {System.out.println ("Myservletfiler Destroy");}}
Second, the filter action sequence
In the front we are mainly focused on a filter, but the actual situation, it is possible (because it is mostly) more than one filter, so the order between the filters is very important, so that the business logic will not be confused. Here we do a test, there are mainly 4 filters, two configurations using the @webfilter configuration, two using the Web. XML configuration. Each filter is printed to identify their initialization, destruction, and filtering, and they all filter on the same resource as follows:
public class MyServletFilter1 implements Filter {public void init (Filterconfig filterconfig) throws Servletexception {Sys Tem.out.println ("MyServletFilter1 init");} public void DoFilter (ServletRequest request, servletresponse response, Filterchain chain) throws IOException, servletexception {System.out.println ("MyServletFilter1 do Filter"); Chain.dofilter (request, response);} public void Destroy () {System.out.println ("MyServletFilter1 Destroy");}}
public Class MyServletFilter2 implements Filter {public void init (Filterconfig filterconfig) throws Servletexception { System.out.println ("MyServletFilter2 init");} public void DoFilter (ServletRequest request, servletresponse response, Filterchain chain) throws IOException, servletexception {System.out.println ("MyServletFilter2 do Filter"); Chain.dofilter (request, response);} public void Destroy () {System.out.println ("MyServletFilter2 Destroy");}}
@WebFilter ( Filtername= "MyServletFilter3", urlpatterns= "/myhttpservlet") public class MyServletFilter3 implements Filter {public void init (Filterconfig filterconfig) throws Servletexception {System.out.println ("MyServletFilter3 init");} public void DoFilter (ServletRequest request, servletresponse response, Filterchain chain) throws IOException, servletexception {System.out.println ("MyServletFilter3 do Filter"); Chain.dofilter (request, response);} public void Destroy () {System.out.println ("MyServletFilter3 Destroy");}}
@WebFilter (filtername= "MyServletFilter4", urlpatterns= "/myhttpservlet") public class MyServletFilter4 implements Filter {public void init (Filterconfig filterconfig) throws Servletexception {System.out.println ("MyServletFilter4 Init ");} public void DoFilter (ServletRequest request, servletresponse response, Filterchain chain) throws IOException, servletexception {System.out.println ("MyServletFilter4 do Filter"); Chain.dofilter (request, response);} public void Destroy () {System.out.println ("MyServletFilter4 Destroy");}}
Both MyServletFilter1 and 2 are configured in Web. XML, and 3 and 4 are configured using annotations.
<filter><filter-name>myServletFilter1</filter-name><filter-class> com.javaservlet.servlet.filter.myservletfilter1</filter-class></filter><filter>< Filter-name>myservletfilter2</filter-name><filter-class> com.javaservlet.servlet.filter.myservletfilter2</filter-class></filter><filter-mapping>< filter-name>myservletfilter2</filter-name><url-pattern>/myhttpservlet</url-pattern></ Filter-mapping><filter-mapping><filter-name>myservletfilter1</filter-name><url-pattern >/myHttpServlet</url-pattern></filter-mapping>
The start order of the filter:
The start order of the filter in the test is always 2143, as if there were no rules, but it can be found that if a filter in a Web application is fixed, the boot order of those filters is constant, unless a new filter is added.
Destroy Order of filter:
The destruction order of the filter in the test is also always 2143, if the filter in a Web application is fixed, which of these filters is in the same order, unless a new filter is added, and the order of destruction of the filter is found to be consistent with the order in which they are started.
Filter's Order of action:
The order in which the filters are called in Web. XML is determined by the filtermapping element, which filter 's filtermapping element is preceded by which filter is first called , not by the filter element.
Third, the dispatcherfilter of the filter has a scope, we usually use the filter action on the request, which is the default value of the Dispatchertypes property in the filter, This property means that the resources managed by the filter are accessed in such a way that it can be request, forward, declarative error, include, and so on, but we can also configure the filter to act on other scopes, which is determined by the Dispatchertypes property, which has the following values:
- Dispatchertype.request
- Dispatchertype.forward
- Dispatchertype.include
- Dispatchertype.error
- Dispatchertype.async
The default value of the Filter property is Dispatchertype.request, because it is an array property, so you can configure multiple values. The configuration method can use annotations, or it can be configured using Web. Xml.
Use annotations:
@WebFilter (filtername= "Myfilter", urlpatterns= "/myhttpservlet", initparams={@WebInitParam (name= "Server", value= " Www.baidu.com "), @WebInitParam (name=" Port ", value=" 443 ")},dispatchertypes={dispatchertype.request, Dispatchertype.forward}) public class Myservletfilter implements Filter {}
Use Web. Xml as follows:
<filter-mapping><filter-name>myservletfilter2</filter-name><url-pattern>/myhttpservlet </url-pattern><dispatcher>ERROR</dispatcher><dispatcher>FORWARD</dispatcher>< Dispatcher>request</dispatcher></filter-mapping>
Note that when configured in Web. XML, the version of the deployment descriptor (Web. xml) used will have this attribute at least 2.3.
A resource that is configured to manage the filter works when it is called directly or through a forward call. We can make calls in the servlet, where there are two servlets to use:
The following servlet is managed by the filter:
@WebServlet (name= "Myhttpservlet", urlpatterns= "/myhttpservlet") public class Myhttpservlet extends HttpServlet { ......}
The following servlet is used to invoke the above servlet:
@WebServlet (name= "MyHttpServlet1", urlpatterns= "/myhttpservlet1", loadonstartup=1) public class MyHttpServlet1 Extends HttpServlet {private static final long serialversionuid = 6446908355902952649L; @Overrideprotected void Doget ( HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {System.out.println (" MyHttpServlet1 request Work "); System.out.println ("Current thread:" + thread.currentthread (). GetName ()); Resp.getwriter (). Write ("MyHttpServlet1") ; Req.getrequestdispatcher ("/myhttpservlet"). Forward (req, resp);//req.getrequestdispatcher ("/myhttpservlet"). Include (req, resp);}
The analysis is as follows:
- When there is no dispatchertype.forward in the filter above, the filter method is not called when the top Getrequestdispatcher () calls forward () to access the Myhttpservlet. Using the Forward () method will only return the last called resource;
- When there is no dispatchertype.include in the filter above, the filter method is not called when the top is called by Getrequestdispatcher () to access the Myhttpservlet. Use the Include () method to return all the resources that have been passed;
Another is the declarative handling of the error, which is configured in Web. XML, as follows:
<error-page><error-code>404</error-code><!--Error-code or exception-type can be chosen only one- -><!--<exception-type>java.lang.NullPointerException</exception-type>--><location>/ Myhttpservlet</location></error-page>
When a 404 error occurs, the servlet corresponding to the/myhttpservlet is accessed, and this filter is not passed if Dispatchertype.error is not configured in the filter.
Related articles:
- Understanding and Using Servlet Filters
- Dispatcher use in filter configuration
- Web. XML templates for each version
Java Web Basics Filter: Filters Everything you don't want to see