tags: spring Interceptor filter
I believe that the small partners who are doing web will often come into contact with the three major Java devices (interceptors, filters, and listeners). When I recently sorted out, I found that I want to be completely clear, but I still have some unclear places. I also learn here. When finishing, it’s just a lack of trapping.Focus: This article is based on the content of the spring framework).
It is not easy to make things clear and understand from beginning to end. Lz feels that it needs to have some relevant knowledge and certain project experience. Otherwise, it is impossible to understand, so lz suggests to understand the following knowledge points. Learning itself is A gradual process, to understand a certain knowledge, requires a reserve of multiple knowledge points:
1. The concept, principle and function of servlet, here are some summary of the predecessors:What is the servlet?,Servlet understanding
2.What is Tomcat doing in Java?
3. Proxy mode and AOP
4. Chain of Responsibility
5. Request and response
EncyclopediaThe concept introduction is very standard:
The interceptor in java is the object that dynamically intercepts the Action call. It provides a mechanism for developers to define code that is executed before and after an action is executed, or to prevent execution before an action is executed. It also provides a way to extract reusable parts of an action. At AOP (Aspect-Oriented
The Programming) interceptor is used to intercept a method or field before it is accessed and then add some operations before or after.
In short, the interceptor in java is the object that dynamically intercepts the Action call. It provides a mechanism for developers to define code that is executed before and after an action is executed, or to prevent execution before an action is executed. It also provides a way to extract reusable parts of an action. In AOP (Aspect-Oriented Programming) interceptors are used to intercept a method or field before it is accessed and then add some operations before or after.
Lz feels that when learning the interceptor, it should be compared with the filter, so that the understanding of important features will be better, not to be confused (filter will be detailed later, no hurry):
Here are two figures
First source
Second source

From the above two figures, the difference between the interceptor and the filter is basically explained, and the trigger timing, that is, the filter is the container level support, and the interceptor is the program framework support.
If you follow the advice of the landlord, first learn the proxy mode and the chain of responsibility model, and have a kind of "sinking, principle is like this" for the AOP based on the proxy mode, then it is very easy to understand the principle of the interceptor. That's right, because the bottom layer of the interceptor mainly uses the AOP idea and the chain of responsibility model!
In springMVC, customizing an interceptor can be divided into two steps:
1. Implement the HandlerInterceptor interface or inherit the abstract class AbstractInterceptor
2. The interceptor defined by the configuration file in your project, usually in dispatcher-servlet.xml
After the Action object is created, the default interceptor is executed before the Action method is executed. The AOP idea is used here. When the interceptor is executed, many interceptors are executed (the default interceptor also has many interceptors), which is the chain of responsibility mode!
Let's take a look at the HandlerInterceptor interface source code.
public interface HandlerInterceptor {
boolean preHandle(HttpServletRequest var1, HttpServletResponse var2, Object handler) throws Exception;
void postHandle(HttpServletRequest var1, HttpServletResponse var2, Object handler, ModelAndView var4) throws Exception;
void afterCompletion(HttpServletRequest var1, HttpServletResponse var2, Object handler, Exception var4) throws Exception;
}
There are three methods defined here:
1.boolean preHandle(HttpServletRequest var1, HttpServletResponse var2, Object handler)
Detailed explanation: ** This method is called before the business processor processes the request. The Interceptor in SpringMVC is chained (ie, the chain of responsibility mode), and multiple Interceptors can exist in one application or in one request. Each Interceptor call is executed in the order in which it is declared, and the first implementation is the preHandle method in the Interceptor, so some pre-initialization operations or a pre-processing of the current request can be performed in this method. You can make some judgments in this method to decide if the request should continue. The return value of this method is Boolean type Boolean. When it returns false, it indicates that the request ends, and the subsequent Interceptor and Controller will not execute. When the return value is true, it will continue to call the next Interceptor preHandle method. If it is already the last Interceptor, it will be the Controller method that calls the current request. ** Usually we implement my login function, write business in this method
2.void postHandle(HttpServletRequest var1, HttpServletResponse var2, Object handler, ModelAndView var4)
Detailed: This method is executed after the current request is processed, that is, after the Controller method is called, but it will be called before the DispatcherServlet returns the view, so we can operate the ModelAndView object after the Controller processing in this method.The direction in which the postHandle method is called is the opposite of preHandle, which means that the postHandle method of the Interceptor declared first will be executed later.。
3.void afterCompletion(HttpServletRequest var1, HttpServletResponse var2, Object handler, Exception var4)
Detailed: This method is also executed when the return value of the current Interceptor's preHandle method is true. As the name implies, this method will be executed after the entire request has finished, that is, after the DispatcherServlet renders the corresponding view. The main function of this method is to carry out resource cleanup work.The direction of the afterCompletion method is also reversed, and the perHandle is executed after the InterCompor method is declared.。
(About the execution order of HandlerInterceptor can be found in the HandlerExecutionChain class, later)
First implement a login function, assuming the project's login request is xx/toLogin, then you need to intercept some requests and check if the login is done:
public classLoginInterceptor implements HandlerInterceptor {
/ / Define the release url, such as static resources, toLogin, etc.
private List<String> urls;
/ / Execute before executing the Controller method
/ / for user authentication verification, user permission check
@Override
public booleanpreHandle(HttpServletRequest request,
HttpServletResponseresponse, Object handler) throws Exception {
/ / Get the requested url
String uri = request.getRequestURI();
/ / Determine whether it is a public address
/ / In actual development, you need to public address configuration in the configuration file
for(String url : urls){
if(uri.indexOf(url)>=0){
// Release if it is a public address
return true;
}else{
return false;
}
}
/ / Determine whether the user identity exists in the session
HttpSessionsession = request.getSession();
Stringusercode = (String) session.getAttribute("usercode");
/ / If the user identity exists in the session release
if(usercode!=null){
return true;
}
/ / Execute here to intercept, jump to the landing page, the user authenticates
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
/ / If it returns false, the interception does not continue to execute the handler, if it returns true, it means release.
return false;
}
/ / After executing the Controller method, return to modelAndView to execute
/ / If you need to provide some public data to the page or configure some view information, use this method to start from modelAndView
@Override
public voidpostHandle(HttpServletRequest request,
HttpServletResponseresponse, Object handler,
ModelAndViewmodelAndView) throwsException {
System.out.println("HandlerInterceptor...postHandle");
}
/ / Complete this method after rendering the page
/ / System unified exception handling, method execution performance monitoring, set a time point in preHandle, set a time in afterCompletion, the difference between the two time points is the execution time
/ / Realize system unified logging
@Override
public voidafterCompletion(HttpServletRequest request,
HttpServletResponseresponse, Object handler, Exception ex)
throws Exception {
System.out.println("HandlerInterceptor...afterCompletion");
}
}
Settings in the configuration file
<!--Interceptor -->
<mvc:interceptors>
<mvc:interceptor>
<!-- /** can intercept the path no matter how many layers -->
<mvc:mapping path="/**" />
<bean class="xxx interceptor 1">
<bean class="xxxinterceptor 2">
<bean class="cn.itcast.ssm.controller.interceptor.LoginInterceptor">
<property name="exceptUrls">
<list>
<value>/tologin</value>
<value>/sys/**</value>
<value>/swagger.html</value>
<value>/swagger-resources</value>
<value>/xxx</value>
<value>/xxx/**</value>
<value>/xxx</value>
</list>
</property>
</bean>
</mvc:interceptor>
</mvc:interceptors>
The basic functions of login are implemented. The above reference materials:
Now, the use of the interceptor is basically mastered, but it is not enough to understand the execution order and principle more deeply. After a few days, I will update the interceptor. . . .
Filter Filter, as the name implies, is a Java class that is executed by the servlet container for each incoming http request and each http response. This way, HTTP incoming requests can be managed bef...
The difference between filters and interceptors In Spring development, we will encounter the use of Filter and Interceptor. They can do some preprocessing on some requests, but there are still big dif...
background: In fact, it is necessary to complete a simple security verification of the calling interface. It seems that it is relatively easy to find out the signature algorithm. After all, the hmac a...
1. Filter What is a filter? You can think of it as a sieve, which filters out some parameters in request and response 1. Import the relevant jar package Import the public jar package in the pom file U...
Filter FILTER is part of the servlet container, part of the Servlet specification, The interceptor is independent, which can be used in any case. Article catalog Filter filter FilterRegistrationBean m...
1, know the filter (Filter) 1.1, definition of the filter The filter is one of the three major components of JavaWeb and is a Java class that implements the Filter interface. The filter is a filter fu...
1. Filter In fact, the filter (Filter) is very similar to Servlet, which is a component of Java. That is, before sending to Servlet, you can intercept and process the request, or you can deal with the...
Spring Filter interceptor configuration Filter can be regarded as a "enhanced version" of Servlet. It is mainly used to pre -process user requests. It can also be postponed by HTTPSERVLESPON...
1. Interceptor definition: The interceptor is applied to cut -faced programming, that is, call a method before your service or a method, or call a method after the method. It is a reflection mechanism...
The difference between interceptor and filter: 1. Interceptor only works on action requests, while filter works on almost all requests. 2. The filter is after the request enters the container (Tomcat)...