[Filter] basic knowledge

Posted by brucec on Sat, 30 Oct 2021 07:45:41 +0200

1._Filter

One of the three major components of Java Web (Servlet, Filter and Listener);

Similar to Servlet, it is used to intercept requests, not to process requests; Web developers use Filter technology to intercept all web resources managed by the web server, such as Jsp, Servlet, static picture file or static html file, so as to realize some special functions. For example, it implements some advanced functions such as URL level permission access control, filtering sensitive words, compressing response information and so on.

The Servlet API provides a Filter interface. When developing web applications, if the Java class written implements this interface, this Java class is called Filter.

The execution status is before the Servlet. When the client sends a request, it will first pass through the Filter and then reach the target Servlet; When responding, the Filter will be executed in reverse again according to the execution process. It can solve the redundancy problem of common codes of multiple servlets (such as garbled code processing and login verification)

2._Filter lifecycle

Init: when the server is started, a Filter instance will be created, and only one instance of each type of Filter will be created, which will not be created from now on. After the Filter instance is created, the init() method will be called immediately to complete the initialization work, and this method will only be executed once;

doFilter: this method will be executed every time the user accesses the target resource (the path in the URL pattern of the configuration Filter in the web.xml file). If "release" is required, the doFilter(ServletRequest,ServletResponse) method of FilterChain needs to be called. If the doFilter() method of FilterChain is not called, the target resource cannot be executed;

Destroy: after creating the Filter object, the server will put the Filter into the cache and use it all the time. Usually, it will not destroy it. Generally, the Filter object will be destroyed when the server is shut down. Before destroying the Filter object, the server will call the destroy () method of the Filter object.

Modify the code of TestFilter to test

public class TestFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
        System.out.println("init...");
    }

    public void destroy() {
        System.out.println("destroy...");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        System.out.println("filter....");
        chain.doFilter(request, response);
    }
}

3._Filter configuration

The configuration of Filter is similar to that of Servlet. There are two configuration methods: xml and annotation.

1. xml configuration

Attention and servlet differentiation

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <filter>
        <!-- filter The name must be the same as that in another group of labels filter Your names match -->
        <filter-name>TestFilter</filter-name>
        <!-- filter Full class name of -->
        <filter-class>com.qfedu.filter.TestFilter</filter-class>
    </filter>
    <filter-mapping>
        <!-- filter The name must be the same as that in another group of labels filter Your names match -->
        <filter-name>TestFilter</filter-name>
        <!-- cover filter Intercepted resources -->
        <url-pattern>/TestServlet</url-pattern>
    </filter-mapping>
</web-app>

2. Annotation configuration

Use the annotation @ WebFilter on the custom Filter class to annotate common attributes:

  • filterName: the name of the filter;
  • value: the address of the filtered target resource.

If @ WebFilter only writes a string, the string Filter filters the address of the target resource.

@WebFilter(filterName = "AFilter", value = "/AServlet")
public class AFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        System.out.println("AFilter...");
        chain.doFilter(request, response);
    }
}

3. Filter path

There are three types of filter paths:

  • Accurately filter matches, such as / index.jsp, / myservlet1;
  • Suffix filtering matching, such as *. jsp, *. html, *. jpg;
  • The wildcard filter matches / *, which means that all are intercepted. Note that the filter cannot be used / matched, / aaa/bbb / * is allowed.

4. Filter chain

After the client requests the server, the server will execute a set of filters (multiple filters) before calling the Servlet. Then this set of filters is called a filter chain.

Each filter implements a specific function. When the doFilter method of the first filter is called, the Web server will create a FilterChain object representing the filter chain and pass it to the method. In the doFilter method, if the developer calls the doFilter method of the FilterChain object, the Web server will check whether there is a filter in the FilterChain object. If so, the second filter will be called. If not, the target resource will be called.

5. Filter priority

In a Web application, you can develop and write multiple filters, which are combined to be called a Filter chain. Priority:

  • If it is an annotation, the action order is determined according to the string order of the full name of the class;
  • For web.xml, follow the filter mapping registration order from top to bottom;
  • web.xml configuration is higher than annotation mode;
  • If the annotation and web.xml are configured at the same time, multiple filter objects will be created, resulting in multiple filtering.

About "if annotations and web.xml are configured at the same time, multiple filter objects will be created, resulting in multiple filters"

4._ Basic use

1. Create a Java Web project

2. Create filter class

@WebFilter(filterName = "AFilter", value = "/AServlet")
public class AFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        System.out.println("AFilter...");
        chain.doFilter(request, response);
    }
}

3. Create filtered classes

@WebServlet(name = "AServlet", value = "/AServlet")
public class AServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("doGet...");
    }
}

Start project, access http://localhost:8080/javaweb__ 01_ war_ Expanded / aservlet will print out "AFilter..." first, then execute the corresponding class and print out doGet

Topics: Java Operation & Maintenance server