[JavaWeb] Listener&Filter listener and filter

Table of contents

1. Overview of the listener

1. What is a listener

2. The purpose of the listener

3. Listener Terminology

Second, the introduction of the monitor

1. The entry program of the listener

2. The execution process of the listener

3. Listener in Servlet

3.1 Introduction to Listener in Servlet

3.2 Classification of listeners in Servlet

3.3 Use of ServletContextListener listener

3.4 Use of HttpSessionListener listener

3.5 Use of ServletRequestListener listener

4. Cases of counting the current number of online users

1. Case Analysis

 2. Code implementation

5. A listener that listens for property changes of three domain objects

6. Listener for monitoring Java class state changes in HttpSession

3. Overview of Filter (filter)

1. What is Filter

2. Why Learning Filters

3. Introduction to Filter

1. The first step: write a class to implement the Filter interface

2. The second step: configure the filter

4. Overview of the FilterChain object

1. What is FilterChain

2. Demo of FilterChain

5. Filter life cycle

6. Overview of the FilterConfig object

1. The role of the FilterConfig object:

2. API of FilterConfig object

3. Demo of FilterConfig

7. Related configuration of filters

4. Case: Authorization Verification Filter

1. Case requirements

2. Case login function

2.1 Create table

2.2 Build the project environment

5. Analysis of common character set encoding filters

1. Case requirements

2. Enhance the method of a class

6. Code implementation of general character set encoding filter


1. Overview of the listener

1. What is a listener

A listener is a Java class that implements a specific interface. This Java class is used to listen to method calls or property changes of another Java class. When the above event occurs on the monitored object, a method of the listener will be executed immediately.

2. The purpose of the listener

Used to monitor changes in other objects. It is mainly used in the development of graphical interface.

  • Java中GUI,Android

3. Listener Terminology

  1. Event source: refers to the monitored object (car)
  2. Listener: refers to the listening object (alarm)
  3. Event Source and Listener Binding: Installing an Alarm on a Car
  4. Event: refers to the change of the event source object (kicked the car) - the main function obtains the event source object.

Second, the introduction of the monitor

1. The entry program of the listener

2. The execution process of the listener

3. Listener in Servlet

3.1 Introduction to Listener in Servlet

Various types of listeners are defined in Servlet, and the event sources they use to listen to are three domain objects: ServletContext, HttpSession and ServletRequest.

3.2 Classification of listeners in Servlet

  1. One class: Listeners that monitor the creation and destruction of three domain objects (three)
  2. The second category: Listeners (three) that listen to attribute changes (attribute addition, removal, and replacement) of three domain objects
  3. Three categories: monitor the state change (passivation, activation, binding, unbinding) of JavaBean in HttpSession (two)

3.3 Use of ServletContextListener listener

3.3.1 The role of the ServletContextListener listener

  • A listener used to monitor the creation and destruction of ServletContext domain objects.

3.3.2 ServletContext creation and destruction

ServletContext:

  • Create: Create a separate ServletContext object for each web application when the server starts.
  • Destroyed: when the server is shut down, or when the project is removed from the web server.

3.3.3 ServletContextListener listener method

1. Monitor the creation of the ServletContext object

 2. Monitor the destruction of the ServletContext object

3.4.4 Listener code

3.4.5 Listener configuration

3.4.6 ServletContextListener enterprise use

  1. Load the configuration file of the framework: The Spring framework provides a core listener ContextLoaderListener.
  2. Timing task scheduling

3.4 Use of HttpSessionListener listener

3.4.1 HttpSessionListener listener function

  • Used to monitor the creation and destruction of HttpSession objects.

3.4.2 HttpSession creation and destruction

  • Creation: When the server calls the getSession() method for the first time.
  • destroy:

        ① Shut down the server abnormally (the server session will be serialized when the server is shut down normally).

        ② Session expires (the default expiration time is 30 minutes).

        ③ Manually call the session.invalidate() method.

3.4.3 HttpSessionListener listener method

1. Monitor HttpSession object creation

2. Monitor the destruction of the HttpSession object

3.4.4 Write a listener to monitor the creation and destruction of HttpSession objects

  • listener code

  • Listener configuration

 3.4.5 Problems

  1. Whether to create a session for accessing HTML: no
  2. Whether to create a Session for accessing JSP: Yes
  3. Whether to create a Session when accessing the Servlet: No (the getSession method is not called by default)

3.5 Use of ServletRequestListener listener

3.5.1 Function of ServletRequestListener listener

The user monitors the creation and destruction of the ServletRequest object

3.5.2 Creation and destruction of ServletRequest object

  • Create: Send a request from the client to the server, and the server will create the request object.
  • Destruction: After the server responds to this request, the request object is destroyed.

3.5.3 ServletRequestListener listener method

  • Monitor the creation of ServletRequest objects

  •  Monitor the destruction of the ServletRequest object

 3.5.4 Write listener code

  • listener code

  • Listener configuration

  •  question:
  1. Whether to create a request object when accessing an HTML page: Yes
  2. Whether to create a request object when accessing a JSP page: Yes
  3. Whether the access Servlet creates a request object: Yes

4. Cases of counting the current number of online users

1. Case Analysis

 2. Code implementation

  • Create a ServletContextListener for initialization

  • Create HttpSessionListener

  • Configure the listener

  •  Create JSP pages

5. A listener that listens for property changes of three domain objects

1.ServletContextAttributeListener

A listener that monitors property changes (property addition, removal, replacement) in the ServletContext object

 2.HttpSessionAttributeListener

A listener that monitors property changes (property addition, removal, replacement) in the HttpSession object

3.ServletRequestAttributeListener

A listener that monitors property changes (property addition, removal, replacement) in the ServletRequest object

4. Demonstrate the second type of listener

Demo of HttpSessionAttributeListener:

  • code writing

  • Configure the listener

  • Write the JSP for the test

6. Listener for monitoring Java class state changes in HttpSession

1. Overview of the third type of listener

The Java class stored in the Session domain can have multiple states: bound to the session; unbound from the session; persisted to a storage device with the session object (passivation); removed from a storage device with the session object Restore (activate).

The Servlet counterpart defines two special monitoring interfaces to help Java classes understand their status in the Session domain :

HttpSessionBindingListener interface

HttpSessionActivationListener interface,

Classes that implement these two interfaces do not need to be configured in web.xml .

2. HttpSessionBindingListener listener:

A listener that monitors the binding and unbinding status of Java classes in HttpSession:

  • Test code:

3. HttpSessionActivationListener listener

Passivation and activation listeners for Java classes that listen to HttpSession.

  • test code

  • Configure the serialization and deserialization of the session

Context tags can be configured in:

tomcat/conf/context.xml : All projects under virtual hosts and virtual directories under tomcat will serialize sessions

tomcat/conf/Catalina/localhost/context.xml : All projects under the localhost virtual host will serialize the session

Project /META-INF/context.xml: Only the current project will serialize the session .

<Context>
<Manager className="org.apache.catalina.session.PersistentManager" maxIdleSwap="1">
	<Store className="org.apache.catalina.session.FileStore" directory="itheima"/>
</Manager>
</Context>

3. Overview of Filter (filter)

1. What is Filter

Filter is called a filter, which is the most practical technology in Servlet technology. Web developers use Filter technology to intercept resources (JSP, Servlet, static pictures or static html files) managed by the web server, so as to achieve some special Function.

Filter is to filter requests sent from the client to the server.

2. Why Learning Filters

3. Introduction to Filter

1. The first step: write a class to implement the Filter interface

2. The second step: configure the filter

4. Overview of the FilterChain object

1. What is FilterChain

FilterChain filter chain: In a web application, multiple Filters can be developed and written, and the combination of these Filters is called a filter chain.

The web server decides which Filter to call first according to the registration sequence of the Filter in the web.xml file (mapping configuration sequence). Invoke the following filters in turn, if there is no next filter, call the target resource

2. Demo of FilterChain

5. Filter life cycle

The creation and destruction of Filter is the responsibility of the web server. When the web application starts, the web server creates an instance object of Filter. And call its init method to initialize (the filter object will only be created once, and the init method will only be executed once).

Every time the filter intercepts, the method of doFilter will be executed.

When the server is shut down, when the application is removed from the server, the server will destroy the Filter object.

6. Overview of the FilterConfig object

1. The role of the FilterConfig object:

The object used to obtain the related configuration of Filter.

2. API of FilterConfig object

3. Demo of FilterConfig

7. Related configuration of filters

1. Configuration of <url-pattern>

  • Full path matching: start with / such as /aaa /aaa/bbb
  • Directory matching: start with / and end with * such as /* /aaa/* /aaa/bbb/*
  • Extension matching: cannot start with / start with * such as *.jsp *.do *.action

2. Configuration of <servlet-name>

Intercept Servlets specifically with the name of the Servlet's configuration.

3. Configuration of <dispatcher>

  • By default the filter will block the request. If forwarding (you need to intercept this forwarding).
  • The value of the dispatcher

       ① REQUEST: Default value. The default filter intercepts the request.

        ② FORWARD: Forward.

        ③INCLUDE: Intercept when the page is included

        ④ERROR: Intercept when the page jumps to a global error page

4. Case: Authorization Verification Filter

1. Case requirements

Now a website needs to have a login function. After the login is successful, it is redirected to the success page in the background (there are many pages in the background). If you are not logged in now, directly enter the background page address in the address bar.

Write a filter: users who are not logged in can be intercepted. (If you are not logged in, go back to the login page. If you are already logged in, let it go.)

2. Case login function

2.1 Create table

create database web05;
use web05;
create table user(
	id int primary key auto_increment,
	username varchar(20),
	password varchar(20)
);
insert into user values (null,'aaa','123');

2.2 Build the project environment

2.2.1 Filter implementation of authority verification

5. Analysis of common character set encoding filters

1. Case requirements

The website needs to submit Chinese data to the background (it may be GET or POST). Chinese processing is processed in different ways according to different request methods.

It is necessary to call the request.getParameter(); method to receive data, but at this time, the data received by either get or post is garbled. Now call the request.getParameter() method, whether it is the Chinese submitted by the get or post request, there are no garbled characters.

2. Enhance the method of a class

Through the above analysis, now enhance the getParameter method of request. The enhanced process should be written in the filter.

1. How to enhance a method in a class?

  • ① Inheritance: You must be able to control the construction of this class.
  • Decorator:
  • The enhanced class and the enhanced class need to implement the same interface.
  • Get a reference to the enhanced class in the enhanced class.
  • Disadvantages: There are too many methods in the interface, and many other methods are rewritten.

③Dynamic proxy: the class needs to implement the interface

6. Code implementation of general character set encoding filter

1. Filter code

2. Enhanced class code

Guess you like

Origin blog.csdn.net/wang_qiu_hao/article/details/126806881