Table of contents
- foreword
- Filter
- Interceptor interceptor
- Aspect Slicing
- Summarize
foreword
You should have heard of filters, interceptors, and aspects , all of which can play the role of truncation and interception . When doing some business needs, I don’t know how to choose . Today I will introduce the differences between them.
Filter
Filters can intercept method requests and responses (ServletRequest request, ServletResponse response), and perform filtering operations on request responses .
Filters depend on the servlet container . In terms of implementation, based on the function callback, it can filter almost all requests, and a filter instance can only be called once when the container is initialized.
The purpose of using filters is to do some filtering operations to obtain the data we want to obtain, such as: modify the character encoding in the filter; modify some parameters of HttpServletRequest in the filter , including: filter vulgar text, dangerous characters, etc. .
Not much to say, first go to the code
and then define two Controllers, a UserController and an OrderController
. Although the Filter filter and the Controller request have been defined, the filter does not work now. You need to configure the Filter, there are two options
The first solution is to add @Component above the Filter
@Component
public class TimeFilter implements Filter
The second scheme configures the registration filter
The feature of the second scheme is that it can refine the URL of which rules are filtered
When we start the application, the filter is initialized and the init function is called back .
Request http://localhost:9000/order/1
to see the console log output
request http://localhost:9000/user/1
console log output
After the application is stopped, the console output
Filter is started with the startup of the web application , initialized only once, and destroyed when the web application is stopped.
1. Load the instance of the filter when starting the server, and call the init() method to initialize the instance;
2. Only ;
3. When the server is stopped , call the destroy() method to destroy the instance.
Let's look at the doFilter method again
doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
From the parameters, we can see that the request parameters and response data can be obtained in the filter ; but this method cannot know which method in which Controller class is executed.
Another thing to note is that the injected bean cannot be used in the filter, that is, the value injected by the code
above @Autowired cannot be null. Why ?
In fact, in Spring, the order of starting web applications is: listener->filter->servlet , first initialize the listener, then initialize the filter, and then initialize our dispathServlet . Therefore, when we need to inject a When the annotated bean is used, the injection will fail, because when the filter is initialized, the annotated bean has not been initialized and cannot be injected.
Interceptor interceptor
Depends on the web framework, in SpringMVC it depends on the SpringMVC framework. In terms of implementation, the Java-based reflection mechanism is an application of aspect-oriented programming (AOP) , which is to call a method before a method, or call a method after a method.
Configure it in WebMvcConfigurationSupport
Execution results
We found that the Controller object can be obtained in the interceptor
preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
The object handler is the controller method object
HandlerMethod handlerMethod = (HandlerMethod)handler;
handlerMethod.getBean().getClass().getName(); //获取类名
handlerMethod.getMethod().getName(); //获取方法名
But we found that the parameter value of the method cannot be obtained, why is this? In the DispatcherServlet class , the method
doDispatch(HttpServletRequest request, HttpServletResponse response)
The applyPreHandle method execution is the preHandler method of the executed interceptor, but in this process, the controller method does not obtain the request parameters from the request and assemble the method parameters; but only assembles the parameters when the ha.handle method is used
Although you can't get the parameters of the method, you can get the IOC bean.
Another point is the postHandler method
The execution of the postHandler method, when there is an exception inside the controller, the posthandler method will not be executed.
The afterCompletion method will execute this method regardless of whether there is an exception inside the controller; this method will also have a parameter Exception ex; if there is an exception, ex will have an abnormal value; if there is no exception, the value is null
Note that if there is an exception inside the controller, but the exception is uniformly caught by @ControllerAdvice exception, ex will also be null
Aspect Slicing
The AOP operation can intercept the operation horizontally. The biggest advantage is that it can obtain the parameters of the execution method and process the method uniformly. Common usage logs, transactions, request parameter security verification, etc.
In the above code, we can get the parameters of the method.
Although the aspect aop can get the method parameters, it cannot get the response and request objects.
Summarize
Let's summarize filters, interceptors, and aspects here to see the difference.
If the three methods are used at the same time, what is their execution order ?
filter -> interceptor -> ControllerAdvice -> aspect -> controller
return value order, or exception return order
controller -> aspect -> controllerAdvice -> Interceptor -> Filter
Use a diagram to describe the execution sequence
You can choose the corresponding technology according to your own business and the respective characteristics of the above technologies.