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 the 10th student of Zhengzhou branch of it Academy. I'm an honest, pure and kind java programmer.

Today, I'd like to share with you the fifth task of Java on the official website of the academy to expand the knowledge points in thinking - what are the functions of interceptors, filters and listeners?

1、 Background introduction

1. Filter

Depends on the servlet container. In implementation, almost all requests can be filtered based on function callback, but the disadvantage is that a filter instance can only be called once when the container is initialized. The purpose of using the filter is to do some filtering operations and obtain the data we want to obtain, such as modifying the character code in the filter; Modify some parameters of HttpServletRequest in the filter, including filtering vulgar text, dangerous characters, etc.

2. Interceptor

It depends on the web framework. In spring MVC, it depends on the spring MVC framework. The implementation is based on java reflection mechanism, It is an application of aspect oriented programming (AOP). Since the interceptor is a call based on the web framework, spring dependency injection can be used (DI) perform some business operations. At the same time, an interceptor instance can be called multiple times within a controller life cycle. However, the disadvantage is that it can only intercept controller requests, and it can not intercept other requests such as direct access to static resources.

3. Listener

Web listener is a special class in servlet, which can help developers monitor specific events in the web and implement javax servlet. The server-side program of servletcontextlistener interface 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 sense the initialization and attribute changes of request (request domain), session (session domain) and applicaiton (application).

2、 Knowledge analysis

1. Use of interceptors

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

The filter only needs to implement handlerinterceptor or webrequestinterceptor and override the corresponding prehandle (...) postHandle(...) And aftercompletion (...) Method.

(1) The prehandle method will be called before the request is processed. Therefore, you can perform some pre initialization operations in this method or preprocess the current request. You can also make some judgments in this method to determine whether the request should continue. The return value of this method is of boolean type. When it returns false, it means that please When the request ends, subsequent interceptors and controllers will not be executed 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 controller method of the current request.

(2) As the name suggests, the posthandle method is executed after the current request is processed, that is, after the controller method is called, but it will be called before the dispatcher servlet renders the view return, so we can operate the modelandview object after the controller processing in this method.

(3) The aftercompletion 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. Use of filter

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

Implement the dofilter method to filter the request or response

Implement the init method and read the initialization parameters of the filter

Destroy(), do some operations when the filter is destroyed

3. Use of listener

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

There are four types and eight types of listener interfaces, which can monitor the generation, destruction and attribute changes of request domain, session domain and application domain

Creation of listening object:

(1) ServletContext: it mainly listens to the creation of ServletContext and needs to implement the servetcontextlistener interface;

(2) ServletRequest: it mainly listens to the creation of request. It needs to implement the ServletRequestListener interface;

(3) Httpsession: it mainly listens to the creation of a session. It needs to implement the httpsessionlister interface

Change of listening attribute:

(1) ServletContext: mainly listens to the change, addition and deletion of ServletContext attributes. The servetcontextattrbutelistener interface needs to be implemented;

(2) ServletRequest: mainly monitors the change, addition and deletion of request attribute, and needs to implement servletrequestattrbutelistener interface; (3) httpsession: mainly monitors the change, addition and deletion of session attribute, and needs to implement httpsessionattrbutelistener interface.

Monitor the activation and passivation of sessions: HttpSessionActivationListener mainly monitors the activation and passivation of sessions.

Listen for binding between session and object: HttpSessionBindingListener listens for binding between session and object.

3、 Common problems and Solutions

What is the difference between interceptors, filters and listeners?

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

(1) Interceptor: intercepting unregistered and audit logs;

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

(3) Listener: count the number of online people and clear expired sessions.

4、 Coding practice

See video for details.

5、 Extended thinking

1. Execution sequence of interceptor, filter and listener

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

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.

3. 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.

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.

6、 References

7、 More discussion

1. How to use custom annotations to implement interceptors?

First, you need to define a custom annotation

@Target(ElementType.METHOD )

@Retention(RetentionPolicy.RUNTIME)

public @interface AccessRequired {

}

ElementType Method indicates that it is effective for the method

RetentionPolicy. RUNTIME

Generally, if you need to dynamically obtain annotation information at runtime, you can only use runtime annotation

Then write your own interceptor, web Configuration is also required in the XML file

Finally, mark the user-defined annotation on the method to be intercepted, indicating that the method needs to be intercepted.

2. If you are not logged in or non VIP, you can try to see how to solve it in 10 minutes?

Segment the video. The first ten minutes is a request, and then request again. Intercept the subsequent request

3. Difference between interceptor and filter:

(1) Interceptors are based on Java's reflection mechanism, while filters are based on function callbacks.

(2) The interceptor does not depend on the servlet container, and the filter depends on the servlet container.

(3) Interceptors can only work on action requests, while filters can work on almost all requests.

(4) The interceptor can access the action context and the objects in the value stack, but the filter cannot.

(5) In the life cycle of an action, interceptors can be called multiple times, while filters can only be called once when the container is initialized

8、 Video tutorial

Join us quickly:

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
分享
二维码
< <上一篇
下一篇>>