This article has participated in the weekend study program, click to see more details
The interceptor:
It is common to see in our daily life, such as China’s Three Gorges Dam on the Yangtze River, which is a typical interception mechanism. It collects a large amount of water, generates electricity and diverts it to output, which not only ensures full utilization of water resources, but also better maintains water cycle and the interests of the people. Because the Yangtze river, as the representative of China’s big rivers, divided into the plentiful water season, in order to better management of the Yangtze river water level, and the effects on the local hydrology, China set up the world’s largest dam, the three gorges dam on the Yangtze river is also reflect an important symbol of China’s national strength, China made the construction of a dam bypass level has lead the world first-class level
Good evening, dry goods, luca to share about the request process of interception, which is more important in our project build configuration, there may be some friends don’t quite understand this, generally we write code may pay more attention to and business implementation, these security configuration and project build, research and development manager may be done directly, but we as developers of the project, Be sure to know all about these;
In fact, as a representative back-end language JAVA, there are three kill, respectively is interceptor, filter, listener
What is the interceptor mechanism
Interceptors are security mechanisms used in user request control for request identification, authentication, and distinguishing whether a resource can be invoked by a target method.
To implement the interceptor, SpringMvc has already integrated it for me. I just need to implement the HandlerInterceptor interface.
If we want to write an interceptor, we need to implement the HandlerInterceptor, the interceptor’s standard interface;
Usage scenarios for interceptors
We often use it in shopping websites, such as Jingdong Mall. After adding shopping cart, if you want to settle accounts, it will jump to the login interface. This is the function of interceptor, judging whether you have logged in successfully, distinguishing the access path, the details are in the three methods of the interface;
Application scenario: Login, authentication, and static resource access
Let’s take login as an example. If the user wants to access personal information and verify whether he/she has logged in or whether the token is valid, then he/she needs to intercept the user/she/he/she to the unlogged page and start the login operation.
package com.atspring.config;
import com.atspring.intercepter.LoginInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/ * *
* Configure the Settings in the Web request
* /
@Configuration
public class AdminWebConfig implements WebMvcConfigurer {
/ * *
* 1. Write an interceptor, register it in the container, and addInterceptors
* 2. Specify an interception rule. If all resources are intercepted, all resources including static resources will be intercepted
* @param registry
* /
// The method to add interceptors in webconfig needs to be overridden
@Override
public void addInterceptors(InterceptorRegistry registry) {
// LoginInterceptor loginInterceptor=new LoginInterceptor();
// registry.addInterceptor(loginInterceptor);
registry.addInterceptor(new LoginInterceptor())
// Add interceptor interceptor path, /** all pass, but in real project may be domain/Lucas /**
.addPathPatterns("/ * *")
// Allow static resources and log in
.excludePathPatterns("/login"."/css/**"."/image/**"."/js/**");
}
}
Copy the code
Configuring interceptors:
package com.atspring.intercepter;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/ * *
* Login check
* 1. Configure the interceptor to block which requests,
* 2. Put the configuration Aop in the container
* /
public class LoginInterceptor implements HandlerInterceptor {
/ * *
* Handle methods before resource requests,
* check etc.
* @param request
* @param response
* @param handler
* @return
* @throws Exception
* /
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// Log in to check
HttpSession session=request.getSession();
Object loginUser = session.getAttribute("loginUser");
if(loginUser! =null){
/ / release
return true;
}
// Interception succeeded
request.setAttribute("message"."Please log in first.");
// Forward to the login page to log in, and return
request.getRequestDispatcher("/login").forward(request,response);
return false;
}
/ * *
* After the processing method, before returning to the page
* For data processing
* @param request
* @param response
* @param handler
* @param modelAndView
* @throws Exception
* /
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
/ * *
* After the request is executed,
* Shutdown of resources, etc
* @param request
* @param response
* @param handler
* @param ex
* @throws Exception
* /
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}
Copy the code
The interceptor executes:
-
1. The interceptor preHandler intercepts the current request and then the target method executes it
-
2. PostHandler executes, returns rendered ModelView information (page information)
-
- Page render afterCompletion
3. Principle of interceptor
1. Find the HandlerExecutionChain based on the current request.
2. Execute the preHandle method of all interceptors in sequence first
- If the current interceptor preHandler returns true. The preHandle of the next interceptor is executed
- If the current interceptor returns false. Execute afterCompletion directly in reverse order for all already executed interceptors;
If either interceptor returns false. Jump out of the target method without executing it
4. All interceptors return True. Implement target method
Execute all interceptors’ postHandle methods in reverse order.
6. Any exception to the previous steps will trigger afterCompletion directly in reverse order
AfterCompletion will also be triggered in reverse order after the page has successfully rendered
conclusion
Interceptor, in the role of the project is silent, on all requests, or customized request interception, authentication, etc., for business process and development is a great contribution to the node power, here the interceptor is mainly based on the configuration of relevant operations in SpringBoot, but the bottom is still springMvc.
I’m going to choose a column this month and continue to output it. It takes a lot of work to make the logo. I’ll finish the article by the end of the week tomorrow.