What are the functions of interceptors, filters and listeners

This is the back-end small class of the monastery. Each article is shared from

[background introduction] [knowledge analysis] [common problems] [solutions] [coding practice] [extended thinking] [more discussion] [References]

Eight aspects of in-depth analysis of back-end knowledge / skills. This article shares:

[what are the functions of interceptors, filters and listeners]

Hello, I'm a java student of Xi'an Branch of it Academy. I'm an honest, pure and kind java programmer. Today, I'd like to share with you the functions of interceptors, filters and listeners

1、 A Background introduction

1. Interceptor

Interceptor is an object that dynamically intercepts action calls. It provides a mechanism for developers to define and execute in an action

You can also block the execution of an action before and after its execution. At the same time, it also provides a method to extract reusable information in action

Part of the way.

2. Filter

Filter implements javax servlet. The server-side program of filter interface is mainly used to filter character coding and do some business logic

It is judged that the filter starts with the start of the web application and is initialized only once. It is destroyed only when the web application is stopped or redeployed

3. Listener

Listener implements javax servlet. Server side program of servletcontextlistener interface,

It is also started with the start of the web application. It is initialized only once and destroyed with the stop of the web application.

The main function is to add some initialization contents and set some basic contents, such as some parameters or

Are fixed objects and so on.

2、 Knowledge analysis

2. Knowledge analysis

Implementation method of Interceptor:

There are two ways: the first is to implement the handlerinterceptor interface, and the second is to implement the webrequestinterceptor interface.

Use of interceptors

Used in the project: write a class to implement the interface + spring MVC To configure interceptors in XML, you only need to implement handlerinterceptor or webrequestinterceptor and rewrite the corresponding prehandle (...) postHandle(...) And aftercompletion (...) Method can

(1) Handlerinterceptor interface

In this interface, three methods are defined, namely prehandle (), posthandle (), and aftercompletion (). These three methods are copied to intercept and process user requests

In addition, another interface and an abstract class are provided in the spring framework to realize the function extension of the handlerinterceptor interface, which are asynchandlerinterceptor and handlerinterceptoradapter

In practical applications, we usually implement the handlerinterceptor interface or inherit the handlerinterceptoradapter abstract class

1) Prehandle method, which is called before the request is processed.

Interceptors in spring MVC are called in a chain, and multiple interceptors can exist simultaneously in a request. The call of each interceptor will be executed in sequence according to its declaration order, and the first execution is the prehandle method. Therefore, some pre initialization operations can be carried out in this method, or the current request can be preprocessed, or some judgments can be made to determine whether the request should continue.

When it returns false, it means that the request ends and the subsequent interceptor and controller will not execute again;

When the return value is true, it will continue to call the prehandle method of the next interceptor. If it is the last interceptor, it will call the method in the controller of the current request.

2) The posthandle method can only be called when the return value of the prehandle method of the current interceptor is true.

After the current request is processed, that is, it is executed after the method call in the controller, but it will be called before the view return rendering by the dispatcher servlet, so you can operate the modelandview object processed by the controller in this method.

The posthandle method is called in the opposite direction to the prehandle. Instead, the declared posthandle method will be executed later.

3) The aftercompletion method is also executed only when the return value of the prehandle method of the current corresponding interceptor is true. Therefore, this method will be executed after the end of the entire request, that is, after the dispatcher servlet renders the corresponding view. The main function of this method is to clean up resources.

(2) Webrequestinterceptor interface

Three methods are also defined in this interface, which are exactly the same as the handlerinterceptor interface. These three methods also need to be copied to intercept the user's request. And the three methods all pass the same parameter webrequest.

The method definition in it is similar to HttpServletRequest. All operations on webrequest in webrequestinterceptor will be synchronized to HttpServletRequest, and then passed in turn in the current request.

1) The prehandle (webrequest request) method is different from the prehandle in handlerinterceptor,

The main difference is that the method has no return value. Therefore, the return value cannot determine whether to terminate the request. Its main function is to prepare resources.

2) The posthandle (webrequest request, modelmap model) method is also after the controller,

The view return is called before it is rendered. This method has two parameters. The webrequest object is used to transfer the entire request data,

For example, the data prepared in the prehandle can be transmitted and accessed through webrequest;

3) the afterCompletion (WebRequest request, Exception Ex) method is also called after the rendering of the view, mainly for the release of resources.

filter

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. Through filter technology, developers can intercept requests and responses before users access a target resource.

There is a dofilter method in the filter interface. After we write the filter and configure which web resource to intercept, the web server will call the dofilter method of the filter before calling the service method of the web resource. Therefore, writing a code in this method can achieve the following purposes:

Let a piece of code execute before calling the target resource;

Whether to call the target resource (i.e. whether to let the user access the web resource);

After calling the target resource, let a piece of code execute.

Use of filters

Used in the project: write a class to implement the interface + web Configuration in XML

The filter only needs to implement javax servlet. Filter, override dofilter (...) init(...) And destroy (..) Method can

When the web server calls the dofilter method, it will pass in a filterchain object,

Filterchain object is the most important object in the filter interface. It also provides a dofilter party. Developers can decide whether to call this method according to their needs,

Then the web server will call the service method of the web resource, that is, the web resource will be accessed, otherwise the web resource will not be accessed.

Methods in filters

Init: when the program starts, the web server will create an instance object of filter and call its init method to complete the initialization function of the object; The filter object is created only once, and the init method is executed only once.

Dofilter: operates on requests when accessing the web server.

Destroy: the web container calls the destroy method to destroy the filter. The destroy method is executed only once in the life cycle of the filter. In the destroy method, you can release the resources used by the filter.

monitor

Monitor web applications, and monitor the initialization, destruction, addition, modification, deletion, etc. of many information.

Listener objects can do some necessary processing before and after things happen.

Classification of listeners

1. ServletContext listening

Servletcontextlistener: used to listen (create and destroy) the entire context of a servlet.

ServletContextAttributeListener: listening for servlet context attributes (adding, deleting and modifying attributes).

The servetcontextattrbutelistener interface needs to be implemented;

2. Session listening

HttpSessionListener interface: monitors the overall status of a session.

HttpSessionAttributeListener interface: listen for session attributes.

It mainly listens to the change, addition and deletion of session attribute. It needs to implement the httpsessionattrbutelistener interface

3. Request listening

ServletRequestListener: used to listen to (create and destroy) request requests.

ServletRequestAttributeListener: listen to the request attribute (add, delete and modify the attribute).

The servletrequestattrbutelistener interface needs to be implemented;

Use of listener

Used in the project: write a class to implement the interface + web Configuration in XML

There are four types and eight types of listener interfaces, including request domain, session domain,

Generation, destruction and attribute change of application domain

Creation of listening object: 1 ServletContext: mainly monitors the creation of ServletContext,

The servetcontextlistener interface needs to be implemented;

2. ServletRequest: mainly listens to the creation of request,

The ServletRequestListener interface needs to be implemented; 3. Httpsession: mainly monitors the creation of sessions,

The HttpSessionListener interface needs to be implemented

3、 Frequently asked questions

What is the difference between interceptors, filters and listeners?

4、 Solution

1. From the point of concern: the filter interceptor scope web requests and make corresponding changes to some information; The listener is used to listen to system level parameters and is generally not changed.

2. For the support relied on: the interceptor needs the support of spring; Filters and listeners need servlet support.

3. Different application scenarios

Interceptor: intercepting unregistered and audit logs;

Filter: set character code, URL level access control, filter sensitive words, compress response information, etc;

Listener: count the number of online people and clear expired sessions

5、 Coding practice

6、 Extended thinking

1. Execution sequence of interceptor, filter and listener?

1. Execution sequence of interceptor, filter and listener

Listener > Filter > interceptor > servlet execution > interceptor > Filter > listener

7、 References

8、 More discussion

Q1: (Qin Yonghui, Xi'an Branch) 2. Execution sequence of multiple interceptors (two)

(1) When both interceptors implement release operation, the order is prehandle 1, prehandle 2, posthandle 2, posthandle 1, aftercompletion 2, aftercompletion 1;

(2) When the first interceptor prehandle returns false, that is, when intercepting it, the second interceptor does not execute at all, and the first interceptor only executes the prehandle part;

(3) When the first interceptor prehandle returns true and the second interceptor prehandle returns false, the order is prehandle 1, prehandle 2 and aftercompletion 1.

Q2: (Guo Jing, Xi'an Branch). Execution sequence of multiple filters

The web server is on the web according to the filter The registration order in XML determines which filter to call first. 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 there is any, The second filter is called. If not, the target resource is called.

Q3: (Qin Yonghui of Xi'an Branch) 4. Execution sequence of multiple listeners

If there are multiple listeners in a webservlet, these servlet listeners are loaded and registered according to the loading order.

Here is the skill tree In it academy, thousands of senior brothers have found their own learning route here. Learning is transparent and growth is visible. Senior brothers have 1-to-1 free guidance. Come and study with me ~ my invitation code is 28769611, or you can click this link directly:

That's all for today's sharing. You are welcome to like, forward, leave messages and make bricks~

Ppt link video link

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>