1. Concept of filter
Filter in Java is not a standard servlet, it cannot handle user requests, nor can it generate responses to clients. It is mainly used for pretreatment of HttpServletRequest, but also for post-processing of HttpServletResponse, which is a typical processing chain.
Advantage: The benefit of the filter chain is that it can be interrupted at any time during execution, as long as no chain.dofilter () is executed and no subsequent filters and requested content are executed. In practical use, we should pay special attention to the execution order of the filter chain.
2. Description of the function of the filter
- Intercept the client's httpservletrequest before HttpServletRequest arrives at the servlet.
- You can also modify the HttpServletRequest header and data as needed to check the httpservletrequest.
- Intercept HttpServletResponse before HttpServletResponse arrives at the client.
- You can modify the HttpServletResponse header and data as needed to check the httpservletresponse.
3. Process of filter execution
Package Test01;import java.io.ioexception;import javax.servlet.filterchain;import javax.servlet.FilterConfig; Import Javax.servlet.servletexception;import javax.servlet.servletrequest;import javax.servlet.ServletResponse; Public classFilter implements Javax.servlet.Filter { PublicFilter () {} Public voiddestroy () {} Public voidDoFilter (servletrequest request, servletresponse response, Filterchain chain) throws IOException, Servletexception {System. out. println ("after the filter 1"); //Set EncodingRequest.setcharacterencoding ("UTF-8"); Response.setcontenttype ("tesx/html"); Response.setcharacterencoding ("UTF-8"); //container for filter chain//Pass the current request to the next filterChain.dofilter (request, response); } Public voidInit (Filterconfig fconfig) throws servletexception {}}
Filter Usage Filter filter