1. What is a filter?

Filter is a filter between the client and the server resource file. Before accessing the resource file, the request is modified and judged through a series of filters, and the requests that do not conform to the rules are intercepted or modified in the middle. Responses can also be filtered, intercepted, or modified.

  • Filters depend on the Servlet container and are part of the Servlet specification.
  • Function callbacks based on Servlet containers are implemented to filter almost all requests.
  • The lifecycle of the Filter is managed by the Servlet container.

2. Filter execution process


Filters are started with the start of the Web application, are initialized only once, and can then intercept requests or responses related to the filter before being destroyed when the Web application is stopped or redeployed.

Let’s learn how to use it with a code example.


3. Application scenario

  • 1. Check whether the user has logged in
  • 2. Set the character encoding uniformly
  • 3. Check whether the page is accessible
  • 4. Filter sensitive characters
  • 5. Etc…

4. Configuration method:

4.1 create a Filter

Enter the filter name, create location.

4.2 Code Analysis

package com.cy.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@WebFilter(filterName = "TestFilter")
public class TestFilter implements Filter {
    /* Call */ for destruction
    public void destroy(a) {}/** * The filter method * processes the request and response, * handing it over to the next filter or Servlet */
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        // Leave it to the next filter or servlet
        chain.doFilter(req, resp);
    }

    /** * Initialize method *@paramConfig receives a parameter of type FilterConfig * which is some configuration of Filter */
    public void init(FilterConfig config) throws ServletException {}}Copy the code

In the code, we can see that a doFilter method is defined in the Filter interface. This method is the method that filters perform the Filter action. Each Filter has access to the filterConfig object and gets initialization parameters from it. Once we have written the Filter implementation class and configured the Web resource to intercept and Filter in the Web application’s deployment descriptor “web.xml,” the Web server will call the doFilter method before calling the Web resource’s service method.

At this point, you can make business logic judgment and processing for web resources (Request and Response) that need to be intercepted and filtered, thus simplifying operations.


4.3 Common Configuration Items

urlPatterns

Configure the resources to intercept

1. Match the specified resource. For example, “/index. JSP “. 2. For example, “/servlet/*”. 3. Match the suffix name, for example, “*.jsp” 4. Wildcard to intercept all Web resources. / *”


initParams

Configure the initialization parameters as the Servlet configuration. For example:

initParams = {
        @WebInitParam(name = "key",value = "value")
}
Copy the code

dispatcherTypes

You can configure multiple interception types. Default value: dispatcherType. REQUEST** For example:

dispatcherTypes = {DispatcherType.ASYNC,DispatcherType.ERROR}
Copy the code

Where DispatcherType is an enumeration type and has the following values

	FORWARD,/ / forward
    INCLUDE,// Included in the page
    REQUEST,/ / request
    ASYNC,/ / asynchronous
    ERROR;/ / error
Copy the code

4.4 Modifying A Code

1. Write a Java class to implement the Filter interface and its methods

package com.cy.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import java.io.IOException;

@webFilter (filterName = "CharsetFilter",urlPatterns = "/*",/* Wildcard (*) means to intercept all Web resources */ initParams = {@webinitParam (name = "charset", value = "utf-8")})/* There are some initialization arguments */
public class TestFilter implements Filter {

    private String url;

    /** * is automatically called when the Filter is destroyed. * /
    @Override
    public void destroy(a) {
        System.out.println("TestFilter destroyed!");
    }


    /** * The filter method * processes the request and response, * handing it over to the next filter or Servlet */
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        long start = System.currentTimeMillis();
        System.out.println(start + " Filter doFilter before...");
        chain.doFilter(req, resp);
        long end = System.currentTimeMillis();
        System.out.println(end + "Filter doFilter after...");
        // Leave it to the next filter or servlet
        chain.doFilter(req, resp);
    }

    /** * Initialize method *@paramConfig receives a parameter of type FilterConfig * which is some configuration of Filter */
    public void init(FilterConfig config) throws ServletException {
        /* The initialization method receives a parameter of type FilterConfig, which is some configuration of Filter */

        this.url = config.getInitParameter("URL");
        System.out.println("Filter init..."); }}Copy the code

Such a simple character set encoding process completes the filter.

4.6 understand

4.6.1 thinking

Are interceptors and filters the same? (Filters are different from interceptors, which are the core in Struts)

4.6.2 Distinguish differences

  1. Filter: When you have a bunch of things, you just want to choose something that meets your requirements. The tool that defines these requirements is the filter. (Meaning: take a “B” from a pile of letters)

  2. Interceptor: When a process is in progress, you want to interfere with its progress, or even stop it from proceeding, which is what interceptors do. (Understanding: in a pile of letters, intervene, pass less verification, and do something else).


The interceptor: Is the aspect oriented programming is at your service, or a method, called before a method, or call a method after the method such as dynamic proxy is the simple implementation interceptors, before you call a method to print out a string (or do other business logic operation), can also print out the string after you call a method, Even do business logic when you throw an exception.

Filter: In javaweb, you pass in request and response to filter out some information in advance, or set some parameters in advance, and then pass in servlet or struts action for business logic, such as filtering out illegal url (not login.do address request, If the user is not logged in, either set a uniform character set before passing in a servlet or struts action, or remove any illegal characters.

The essential difference between the two: from the flexibility of the interceptor function more powerful, interceptor is an IMPLEMENTATION of AOP, the bottom through dynamic proxy mode, Filter can do things, he can do, and can be before the request, request after execution, more flexible. The Filter is mainly for the URL address to do a coded thing, Filter out useless parameters, security check (more general, such as login or not login), too fine, or recommended to use interceptor. But still choose the right one according to different circumstances.


4.6.3 Application Scenarios

SpringMVC’s processor interceptor is similar to the Filter in Servlet development for pre – and post-processing of the processor.

1. Log recording: Logs of request information are recorded for information monitoring, information statistics, and Page View (PV) calculation.

2. Permission check: For login detection, enter the processor to check whether you have logged in. If you do not return to the login page directly;

3, performance monitoring: sometimes the system is inexplicably slow in a certain period of time, you can use the interceptor to record the start time before entering the processor, record the end time after processing, so as to get the processing time of the request (if there is a reverse proxy, such as Apache can automatically record);

4, general behavior: read cookies to get user information and put user objects into the request, so as to facilitate the use of the subsequent process, and such as the extraction of Locale, Theme information, as long as multiple processors need to use interceptors.

5. OpenSessionInView: such as Hibernate, open the Session after entering the processor, and close the Session after completion.