Filter, FilterChain, and FilterConfig Introduction
Category Programming Technology
I. Basic Working Principle of Filter
- A Filter program is a Java class that implements a special interface, similar to Servlet, and is also called and executed by the Servlet container.
- When a Filter is registered in web.xml to intercept a Servlet program, it can decide whether to continue passing the request to the Servlet program and whether to modify the request and response messages.
- When the Servlet container starts to call a Servlet program, if it finds that a Filter program has been registered to intercept the Servlet, the container no longer directly calls the Servlet's service method but calls the Filter's doFilter method, which then decides whether to activate the service method.
- However, the service method of the Servlet cannot be directly called in the Filter.doFilter method, but the FilterChain.doFilter method is called to activate the service method of the target Servlet. The FilterChain object is passed through the parameters of the Filter.doFilter method.
- As long as some program code is added before and after the call to the FilterChain.doFilter method in the Filter.doFilter method, special functions can be implemented before and after the Servlet response.
- If the FilterChain.doFilter method is not called in the Filter.doFilter method, the service method of the target Servlet will not be executed, and thus the Filter can prevent some illegal access requests.
II. Filter Chain
- Multiple Filter programs can be registered in a Web application, and each Filter program can intercept one or a group of Servlet programs. If multiple Filter programs can intercept the access process of a Servlet program, when an access request for that Servlet arrives, the Web container will combine these multiple Filter programs into a Filter chain (also called a filter chain).
- The interception order of each Filter in the Filter chain is consistent with their mapping order in the web.xml file. The Filter.doFilter method in the previous Filter calls the FilterChain.doFilter method to activate the next Filter's doFilter method, and the last Filter.doFilter method calls the FilterChain.doFilter method to activate the target Servlet's service method.
- As long as any Filter in the Filter chain does not call the FilterChain.doFilter method, the service method of the target Servlet will not be executed.
III. Filter Interface
A Filter program is a Java class that must implement the Filter interface. The javax.servlet.Filter interface defines three methods: init, doFilter, and destroy.
1. init Method
(1) When the Web application starts, the Web server (Web container) will create an instance object for each registered Filter according to its web.xml configuration information and save it in memory.
-
(2) After the Web container creates an instance of the Filter, it immediately calls the init method of the Filter object. The init method is executed only once in the life cycle of the Filter, and when the Web container calls the init method, it passes a FilterConfig object containing the configuration and runtime environment information of the Filter.
public void init(FilterConfig filterConfig) throws ServletException
- (3) Developers can complete initialization similar to the constructor in the init method. It should be noted that if the initialization code needs to use the FilterConfig object, this code can only be written in the init method and not in the constructor (the init method has not been called yet, that is, the FilterConfig object has not been created, and using it will inevitably cause an error).
2. doFilter Method
When a Filter object can intercept an access request, the Servlet container will call the doFilter method of the Filter object.
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws java.io.IOException, ServletException
Here, the parameters request and response are the request and response objects passed by the Web container or the previous Filter in the Filter chain; the parameter chain represents the current Filter chain object.
3. destroy Method
This method is called before the Web container unloads the Filter object and is executed only once. It can complete the opposite function of the init method, releasing resources opened by the Filter object, such as closing database connections and IO streams.
IV. FilterChain Interface
This interface is used to define the methods that a Filter chain object should provide to the outside world, and this interface only defines a doFilter method.
public void doFilter(ServletRequest request, ServletResponse response) throws java.io.IOException, ServletException
The doFilter method of the FilterChain interface is used to notify the Web container to hand over the request to the next Filter in the Filter chain for processing. If the current Filter object calling this method is the last Filter in the Filter chain, then the private FilterConfig filterConfig = null; String paramValue = null;
@Override public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; paramValue = filterConfig.getInitParameter("encoding"); }
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("begin headers-------------------"); Enumeration<?> headerNames = ((HttpServletRequest)request).getHeaderNames();
while(headerNames.hasMoreElements()) {
String headerName = (String)headerNames.nextElement();
System.out.println(headerName + ": " + ((HttpServletRequest)request).getHeader(headerName));
}
System.out.println("end headers-------------------");
//Write response content before calling the target
response.setContentType("text/html; charset=gb2312");
PrintWriter out = response.getWriter();
out.println("IP address is: " + request.getRemoteHost() + "<br>");
chain.doFilter(request, response);
//Write response content after the target returns
out.println("<br>The value of the initialization parameter named encoding is: " + paramValue);
out.println("<br>The real path of the current web application is: " + filterConfig.getServletContext().getRealPath("/"));
//out.println("<br>Modified the test.html file!");
}
@Override public void destroy() { this.filterConfig = null; }
## web.xml
<filter> <filter-name>FirstFilter</filter-name> <filter-class>FirstFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>GB2312</param-value> </init-param> </filter>
<filter-mapping> <filter-name>FirstFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
## test.html (located in the filter directory of the WebContent path)
<html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> This is the original content of the test.html page! </body> </html> ```
Access: http://localhost:8888/testFilter_001/filter/test.html
>
Article source: https://my.oschina.net/u/1171518/blog/265467
** Click to share notes
-
-
-
English: