Java Filter (IMOOC learning)
definition : A filter is a server-side component that intercepts the client's request and response information and filters the information.
Working principle
1. Load the Web container when it starts up in the filter
2. The filter exists between the user request and the Web resource
3. The "Send and receive" of User request and Web resource response are filtered by filter according to "Filtering rules"
Life cycle
Instantiation--"initialize--" filter--"destroy
web.xml Init () DoFilter () Destroy ()
Web. XML configuration
First Filter Instance
1. Configure Web. xml
<filter> <filter-name>myfilter</filter-name> <filter-class>firstfilter</ filter-class> </filter> <filter-mapping> <filter-name>myfilter</ filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
2. Write a class base filter
public class Firstfilter implements Filter{public void Destroy () {System.out.println ("destroy ..."); public void DoFilter (ServletRequest request, Servletresponse Response,filterchain chain) throws IOException, servletexception {System.out.println ("Start filter ..."); Chain.dofilter (request, response); System.out.println ("End Filter");} public void init (Filterconfig filterconfig) throws Servletexception {System.out.println ("init ....");//tomcat server runs when loading , can read Web. XML}}
When Tomcat boots, Output init, enter index.jsp in the browser, output start Filter,end filter, turn Tomcat off and execute destroy
Java Web Filter