Spring MVC filters, interceptors, listener

I. Background
1. Filter

It depends on the servlet container. Callback-based, it may be filtered with virtually all in the realization, but the drawback is a filter instance can be called once when the container is initialized. The purpose of the filter is used to do some filtering to get the data we want to get, such as: modify the character encoding in the filter; HttpServletRequest modify some parameters in the filter, including: a filter vulgar words, dangerous characters, etc. .

2. interceptor

Depends on the frame web, it is dependent on the SpringMVC in SpringMVC frame. Based on the Java reflection mechanism, belongs using Aspect Oriented Programming (AOP) is. Since the interceptor is invoked based web framework, it is possible to use Spring dependency injection (DI) for a number of business operations, while an interceptor instance can be called multiple times in the life cycle of a controller. But the drawback is that only on controller request to intercept a request for some other static resources such as direct access is no way to intercept processing.

3. Listeners

web Listener Servlet in a special class, they can help web developers to monitor specific events, implements server-side program javax.servlet.ServletContextListener interface, which is also a web application is launched and starts, initialization only once, with the web application and stop the destruction. The main role is: sensing a change comprises a request (request field), session (session domain) and Applicaiton (application) initialization and properties.

Second, knowledge analysis
using 1. interceptors

Used in the project: write a class that implements the interface configuration + springMVC.xml
1
filter need only implement HandlerInterceptor or WebRequestInterceptor, rewrite the preHandle (...), postHandle (... ) and afterCompletion (...) method may be.

(1) preHandle method will be called before the request processing. This method can be performed in some of the pre-initialization or is a pre-current request, some judgment may be performed to determine whether the request should be continued in this method. The return value of this process is Boolean Boolean type, when it returns to false, indicating the end of the request, and the subsequent Interceptor Controller will no longer performed; when the return value is true preHandle will continue to call a method in the Interceptor If a Interceptor is the last time will be calling Controller method the current request.

ModelAndView object (2) postHandle method, by definition is after the current request is processed, which is executed after Controller method call, but it would be to be called before the view returns rendered DispatcherServlet, so we can Controller processed in this method after operation.

Performed after (3) afterCompletion method after the entire request, that is a corresponding view DispatcherServlet rendering. The main role of this method is that the resources for clean-up work.

2. Use of the filter

Used in the project: writing a class that implements the interface to configure + web.xml

Filter need only implement javax.servlet.filter, rewriting doFilter (...), init (...) and the destroy (...) method may be

DoFilter implemented method, filtering is done on the request or response

Init method implemented, the read filter initialization parameters

destroy (), when the destruction of the filter do something

3. Use of listeners

Used in the project: writing a class that implements the interface to configure + springMVC.xml

Listener interface There are four categories of eight kinds, including the request can monitor domain, session domain, resulting in application domains, change and destruction of property

Listener objects created:

(1) ServletContext: create servletContext main monitor, you need to realize ServeltContextListener interfaces;

(2) ServletRequest: the main listening request is created, the need to achieve ServletRequestListener interfaces;

(3) HttpSession: Creating main listening session, the need to implement the interface HttpSessionListener

Monitor changes in property:

(1) ServletContext: change the primary monitor servletContext properties, add, delete, ServeltContextAttrbuteListener need to implement the interface;

(2) ServletRequest: change the primary monitor request attributes, add, delete, ServletRequestAttrbuteListener need to implement the interface; (3) HttpSession: Change the primary listening session attributes, add, delete, HttpSessionAttrbuteListener need to implement the interface.

Activation and passive listening session: httpSessionActivationListener session mainly monitor the activation and deactivation.

Listening session with the target binding: httpSessionBindingListener listening session is bound to the object.

Third, the common problems and solutions
blocker, filter, what is the difference between the listener?

1. From the point of concern is: filter web request scoped interceptors, and some of the information to make the appropriate changes; the role of the listener listens to the system-level parameters, generally do not change.

2. rely on for support: Spring's interceptor needs support; filters, listeners need to support the servlet.

3. different application scenarios

(1) blockers: intercepting unregistered, audit logs;

(2) Filter: Set Character Encoding, URL-level access control, filtering sensitive words, in response to the compression information and the like;

(3) the listener: the number of online statistics, remove expired session.

Fifth, expand think
the order of execution 1. blocker, filter, listener

Listeners> Filters> Interceptors> servlet execution> Interceptors> Filters> Listener

2. The order of execution of a plurality of interceptors (two)

(1) when the two interceptor release operations are implemented, the order preHandle 1, preHandle 2, postHandle 2, postHandle 1, afterCompletion 2, afterCompletion 1;

(2) when the first interceptor preHandle returns false, i.e. intercepts the second interceptor is completely performed, performing the first interceptor only preHandle portion;

(3) returns true if the first interceptor preHandle, second interceptor preHandle returns false, order preHandle 1, preHandle 2, afterCompletion 1.

3. The order of execution of a plurality of filters

web server according to the registration order Filter in web.xml, decided to call Filter which, when the first Filter doFilter method is invoked, the web server will create a chain of FilterChain Filter objects passed to the method represented in doFilter method , the developer if you call a method doFilter FilterChain object, the web server checks whether there are objects FilterChain filter, if so, calls the second filter, and if not, then call the target resource.

4. The order of execution of a plurality of listeners

WebServlet which if a plurality of listeners, then the sequence is loaded in order to load and register these servlet listener.

Six, reference
https://blog.csdn.net/c_royi/article/details/80563131

http://www.r9it.com/20171127/filter-interceptor-lisener.html
https://blog.csdn.net/java_zhaoyanli/article/details/43406385
https://www.cnblogs.com/HigginCui/p/5772514.html

https://blog.csdn.net/fugushiba/article/details/79745398

Seven more discussion
1. how to use custom annotation implement the Interceptor?

First you need to define a custom annotation

@Target(ElementType.METHOD )

@Retention(RetentionPolicy.RUNTIME)

public @interface AccessRequired {

}

Here is an effective method of representation ElementType.METHOD

RetentionPolicy.RUNTIME

If you need to get the general dynamic annotation information at run time, it would only use RUNTIME comment

Then write your own interceptors, web.xml file also needs to be configured

Finally custom annotation marked on the methods needed to intercept, expressed the need to intercept this method.

2. Non-vip or not logged in, you can Look 10 minutes how to solve?

The video segments, the first ten minutes is a request, after a request again, intercepting behind this request

3. The interceptor filter difference:

(1) is based interceptor java reflection mechanism, and the filter is based on a callback function.

(2) does not rely on interceptors servlet container, and the filter dependent servlet container.

(3) a request interceptor acts only on the action, the filter can act on almost all the requests.

(4) action interceptors can access context, the value of the stack of objects, and the filter can not be accessed.

(5) the action of the life cycle, the interceptor can be called multiple times, and the filter can only be called once when the container is initialized

Released four original articles · won praise 1 · views 39

Guess you like

Origin blog.csdn.net/qq_40813259/article/details/104656881
Recommended