First, Filter

What is a filter?

The filtration period is just like the things we use to filter things in life, to drink tea, to filter tea with gauze. On the Web, when our browser accesses a server, the request sent by the browser is first intercepted by the filter, allowing the filter to perform some action. In practical development, common uses of filters include login authentication, uniform encoding processing, filtering sensitive characters, and so on

Introduction to 2.

To create a Filter, simply create a Java class that implements the Filter interface, override the three methods init, doFilter, destroy, and configure the intercepting path.

First, the inti and Destroy methods are the same as servlets. They are executed once when the server loads and destroys resources. Inti is usually used to load resources, but after the server shuts down properly, the Filter object is destroyed and destroy is executed once to release resources

For doFilter, it is executed every time it requests to intercept a resource, so it is executed multiple times. Note that this method takes three parameters, the first two of which are familiar, and the third parameter, FilterChain, is an interface in which the doFilter method is defined. What’s going on here? Think of it this way: there is not only one filter, but a chain structure is used in Java. Put all the filters in the FilterChain, and if the conditions are met, the next filter is executed (if there are no filters, the target resource is executed).

3. Execute the process

  1. Filter first
  2. Resources after being released
  3. Finally, go back and execute the rest of the code below the release code

4. Configure an interception path

4.1 Annotation Configuration method

To use the annotation method to configure the interceptor path, you need to prefix Filter with @webfilter () parentheses to the interceptor path. If you write only the interceptor path, you can omit the parameter name, because the default is value/urlPattern. If you want to set other parameters, you need to add the parameter name. To filter some Web resources, you need to specify the name of the Web resource.

To specify how resources intercepted by filters are called by the Servlet container, you can set dispatcherTypes to: REQUEST(default), dispatcherType. ERROR, dispatchertype. FROWARD, dispatchertype. INCLUDE, dispatchertype. ASYNC The corresponding values are as follows:

  • REQUEST: the default value. The browser requests the resource directly
  • FORWARD: forwards access resources
  • INCLUDE: includes access to resources
  • ERROR: Indicates an ERROR redirect resource
  • ASYNC: accesses resources asynchronously

4.2 Web. XML Configuration Method

In web.xml, add the following code: filter registers the filter, even implementing the class Filter interface is useless if it is not configured

<filter>
	<filter-name>Set a filter name</filter-name>
	<filter-class>The global name of the Filter to be configured</filter-class>
    <! -- The initial parameter used to specify the filter, which can be obtained by filterConfig in init -->
    <init-param>
        <param-name>word_file</param-name>	
        <param-value>/WEB-INF/word.txt</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>Corresponding to the filter name above</filter-name>
    <url-pattern>Setting interception Path</url-pattern>
    <dispatcher>? Specify Filter to intercept multiple calls to a resource (default REQUEST)</dispatcher>
    <servlet-name>Filters the resource name of the specified servlet</servlet-name>
</filter-mapping>
Copy the code

5. Execution order of multiple filters (filter chain)

  • Filter 1
  • Filter 2
  • Filter 3
  • Execution target resource
  • The rest of the code for filter 3
  • The rest of the code for filter 2
  • The rest of the code for filter 1

What is the order in which filters are executed?

  1. If the web. XML configuration is used, the filter written first in the filter-mapping will be executed first, and the filter written later will be executed later.
  2. If the annotation configuration is used, the class name of the filter is compared, and the smaller value is executed first. For example, if a is less than B, the filter a is executed first

6. Simple application of filters

6.1 Disabling Browser Caching

@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
    // Only HttpServletResponse can set response messages, so we generally convert them to Http
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) resp;

    // Disable caching
    response.setDateHeader("Expires", -1);
    response.setHeader("Cache-Control"."no-cache");
    response.setHeader("Pragma"."no-cache");

    chain.doFilter(request, response);
}
Copy the code

The response header is:

6.2 Automatic Login

6.3 Coding Filter

  • The Request object can be enhanced by implementing the HTTP ServletRequestWrapper class

6.4 Filtering sensitive words

  • Sensitive term filtering can be implemented using dynamic proxies

6.5 Compressing Resource Filters

6.6 HTML Escape Filters

6.7 Caching Data to the Memory

Second, the Listener

What is a listener?

A listener is an ordinary Java program that implements a specific interface. This program is specifically used to listen for method calls or property changes on another Java object. When the listener has the above event, a listener method will be executed immediately.

Event monitoring mechanism

  • Event source: The object on which the event occurs, that is, the object on which it is listened

  • Event object: Encapsulates event sources and actions

  • Event listeners: Event objects are passed in and developers write listener objects to handle them

  • Register listeners: Associate listener objects with the event source

Built-in listener

There are several types of listeners defined in the Servlet specification, which are used to listen for the event sources of three domain objects: ServletContext, HttpSession, and ServletRequest

Servlet listeners are registered not on the event source but on the Web container, and we just need to configure the tags in web.xml

Creation and destruction of listener objects

HttpSessionListener, ServletContextListener, and ServletRequestListener listen for the creation and destruction of Session, Context, and Request objects, respectively

  • HttpSessionListener(which can be used to collect online information)
  • ServletContextListener(to get the parameter configuration in web.xml)
  • ServletRequestListener

Listen for changes in object properties

ServletContextAttributeListener, HttpSessionAttributeListener, ServletRequestAttributeListener Listen for changes to the Context, Session, and Request object properties

The three interfaces define the following three methods to handle the addition, deletion, and replacement of attributes in the monitored object. The same event has the same legal name in the three interfaces, but accepts different types of parameters:

  • attributeAdded()
  • attributeRemoved()
  • attributeReplaced()

Listen for objects in the Session

In addition to the above 6 listener, there are two listener listening Session object: HttpSessionBindingListerner and HttpSsessionActivation:

  • HttpSessionBindingListener: the JavaBean object can be perceived that they were bound to the Session and event of deleted from the Session (and HttpSessionAttributeListener effect is the same)
  • HttpSessionActivationListener: JavaBend objects can sense their own activation and passivation events (Session contents are saved on hard disk when the server is down **[passivation], and Session contents are reloaded on hard disk when the server is on [activation]**)

To test Session hardening and passivation, you need to modify the Tomcat configuration. Add the following code to the context. XML file in meta-INF:

<Context>
	<Manager className="org.apache.catalina.session.PersistentManager" maxIdleSwap="1">
		<Store className="org.apache.catalina.session.FileStore" directory="linzeliang"/>
    </Manager>
</Context>
Copy the code

Application of listeners

  • Count the number of online users
    • Listen to whether a Session is created
    • If a Session is created, the value of the number of people in the Context field object is +1
    • If the Session is removed, the value is -1
  • Custom Session scanner
    • Listen for Session and Context creation
    • Use a container to hold the Session
    • Periodically scan the container for sessions and remove them if they have not been used for a long time
  • Online play man
    • We also use containers to hold sessions
    • List users
    • You can optionally drop the listed user (Session), that is, delete the Session