Spring’s interceptors are similar to Servlet’s filters in that both embody AOP programming ideas and can implement permission checking, logging, and so on. But there are many differences between them, many friends work for many years, may not have a profound understanding of their specific use and the difference between them. This article gives you a comprehensive overview of their use, implementation mechanisms and differences.
Filter (Filter) detailed explanation and use
Filter belongs to the category of Servlet, which can be considered as an “enhanced version” of Servlet. It realizes functions by implementing javax.servlet.Filter interface. It is mainly used to preprocess user requests and is a typical processing chain. Common application scenarios: Checking user authorization, recording log information, decoding, and filtering character encoding.
Basic working principle: After the filter is configured and the Request to be blocked, the method provided by the filter can process the Request or Response in a unified manner when the Request arrives. For example, it can determine whether the user is logged in or has requested access rights. When the Web application starts, the filter is initialized only once to process subsequent requests and destroyed only when the Web application is stopped or redeployed.
The complete process of using Filter is: Filter “preprocesses” the user request, then sends the request to the Servlet for processing and generating the response, and finally Filter “postprocesses” the server response.
1. Filter intercepts the ServletRequest before ServletRequest reaches the Servlet; 2. Check the ServletRequest as needed, or modify the ServletRequest header and data; 3. Intercepting the ServletResponse before it reaches the client; 4. Check the HttpServletResponse as needed and modify the HttpServletResponse headers and data.
To create a Filter, you must implement the Javax.servlet. Filter interface, which defines three methods:
- Void init(FilterConfig FilterConfig) : called when the container initializes the Filter, only once during the entire lifecycle. It can be used to initialize the Filter.
- Void doFilter(ServletRequest Request, ServletResponse Response,FilterChain chain) : This method is used to add additional processing to each request. Calls the next filter with its argument FilterChain.
- Void destroy() : reclaiming certain resources before Filter destruction.
Among them, doFilter method is to realize the pre-processing of user request (ServletRequest Request) and post-processing of server response (ServletResponse Response). The dividing line between preprocessing and post-processing is whether chain.dofilter () is called. Before this method is executed, the user request is preprocessed, and after this method is executed, the server response is postprocessed.
Here is a concrete implementation code to show:
public class LogFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException {system.out. println("Filter initialization "); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain FilterChain) throws IOException, ServletException {system.out. println("Filter preprocessing "); filterChain.doFilter(servletRequest, servletResponse); System.out.println("Filter "); } @override public void destroy() {system.out.println (" container destroy "); }}Copy the code
The use of filters in common Web projects can be configured in web.xml:
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>com.secbro2.learn.filter.LogFilter</filter-class>
<async-supported>true</async-supported>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Copy the code
In the case of a SpringBoot project, LogFilter is instantiated using @Component and then configured using the following configuration file:
@Configuration public class FilterConfig { @Resource private LogFilter logFilter; @Bean public FilterRegistrationBean<Filter> registerAuthFilter() { FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>(); registration.setFilter(logFilter); registration.addUrlPatterns("/*"); registration.setName("authFilter"); // The smaller the value, the more advanced the Filter registration.setOrder(1); return registration; }}Copy the code
Define a Contoller and start the project, access the Controller, and close the project in sequence.
Filter initialization -- above is printed when the project is started -- Filter preprocessing business logic Filter post-processing in Controller -- above is printed when the Controller is accessed -- Container destruction -- above is printed when the service is closed --Copy the code
The details and use of Interceptor
Interceptor, used in AOP(aspect-oriented Programming) to intercept a method or field before it is accessed and then add some action before or after it. Interceptors, as objects that dynamically intercept Action calls, provide a mechanism for developers to define executable code before and after an Action is executed, and to prevent Action execution before it is executed.
Interceptors isolate Action shared behavior and execute it before and after the Action is executed. Common application scenarios include permission management and log service.
To use in the middle of the Spring MVC interceptor needs to implement org. Springframework. Web. Servlet. HandlerInterceptor interface, this interface defines the following three methods:
(1) The preHandle (HttpServletRequest Request, HttpServletResponse Response, Object Handle) method is called before the request is processed. The SpringMVC Interceptor is called in chain form, and there can be multiple interceptors. Interceptor calls are executed in the order they are declared. The first one is the preHandle method, which can be used for some pre-processing and also for determining whether to continue execution. When the return value is false, the request is complete, and the Interceptor and Controller will not be executed again. When the return value is true, the next Interceptor’s preHandle method is called, and the requested Controller method is called when the last Interceptor is finished.
PostHandle (HttpServletRequest Request, HttpServletResponse Response, Object Handle, ModelAndView ModelAndView) Is called after the Controller method is called and before the DispatcherServlet renders the view, so you can operate on the ModelAndView object after the Controller handles it. The postHandle method is called in the opposite direction from the preHandle method. The postHandle method of the Interceptor declared first will be executed later.
AfterCompletion (HttpServletRequest Request, HttpServletResponse Response, Object Handle, Exception ex) Is called after the entire request is complete, that is, after the DispatcherServlet has rendered the corresponding view. The main purpose of this method is to clean up resources.
Let’s look at a concrete example:
@Component public class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { System.out.println("Interceptor preHandle"); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) { System.out.println("Interceptor postHandle"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { System.out.println("Interceptor afterCompletion"); }}Copy the code
The corresponding LoginInterceptor needs to be added to Spring MVC:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Resource
private LoginInterceptor loginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginInterceptor).addPathPatterns("/**");
}
}
Copy the code
This intercepts all requests and after executing the corresponding Controller, you will see the following message printed:
The Interceptor preHandle Controller handles the business logic. The Interceptor postHandle Interceptor afterCompletionCopy the code
Obviously, when a request comes in, the preHandle method, the business in the Controller, the postHandle method, and the afterCompletion method are executed in sequence.
Differences between filters and interceptors
Now that we have a basic understanding of the use and functionality of filters and interceptors, we can feel some of the differences between them. Taking a look at this diagram will make it more obvious where and when filters and interceptors are being used.
To sum it up:
1. The scope of use is different from the specification: Filters are defined in the Servlet specification and can only be used in Web applications, depending on the Servlet container. Interceptors are Spring components that can be used with Web applications, Applications, Swing, and so on, independent of the Servlet container.
2. Different resources: Interceptors can use any resources and objects in Spring, such as Service objects, data sources, transaction management, etc., which can be injected into interceptors through IOC. Filter does not.
3. Different scope: Filter only works before and after the Servlet. Interceptors, on the other hand, can drill down to and from methods, throw exceptions, request Action, access Action context, objects in the value stack, and so on, with greater flexibility. Therefore, interceptors are preferred throughout the Spring framework. Filters work on almost any request.
4. Different implementation mechanisms: Interceptors are based on Java’s reflection mechanism, while filters are based on function callbacks.
The basic differences between filters and interceptors have been described above, but the above figure is further refined to obtain the following image:
In the figure above, we can take a closer look at where the interceptor and filter methods are in the overall request process.
summary
From the above, you have already mastered the basic use of filters and interceptors. Finally, when is it appropriate to use filters and when is it appropriate to use interceptors? Filters are used when some information needs to be filtered out and only some information is left. Interceptors are used when changes need to be made to their processes and relevant documentation is made.
Recently, my personal video number “Ershi Brother…” It has also been updated, one point per minute, and recently it has been updated on the JVM. Some things you don’t know, you just don’t know. Video number “Two Brothers…” Is to solve the problem we don’t know, want to get a good offer, know some other people don’t know the core knowledge, just pay attention to it.
Program new horizon
\
The public account “program new vision”, a platform for simultaneous improvement of soft power and hard technology, provides massive information
\