This is the seventh day of my participation in the August More text Challenge. For details, see:August is more challenging
The SpringBoot Interceptor provides an introduction to the use of Interceptor
Interceptors and Filters seem to have similar application scenarios in SpringMVC. The biggest difference is probably that the former is a Spring feature, while the latter is one of the Servlert three musketeers. The essential difference is that the timing of the two is different
- Filter: the Filter is executed before the Servlet#service method is executed; It will also be filtered after execution
- Interceptor: Intercepts the session by firing a callback three times before the Handler method is called, before the view is rendered, and before the method returns
Depending on the trigger time above, the two can do different things
- The Filter: Request/Response operation
- Interceptor: operation Request/Response/handler/modelAndView/exception
The next part of this article will take a look at how interceptors are used in SpringMVC
I. Project setup
1. Project dependency
This project is developed with SpringBoot 2.2.1.RELEASE + Maven 3.5.3 + IDEA
Start a Web service for testing
<dependencies>
<! -- Core dependencies for mail delivery -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
Copy the code
II. The interceptor
1. Customize interceptors
To implement a custom interceptor, in general, implement the HandlerInterceptor interface
@Slf4j
public class SecurityInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// The request header must contain req-name: yihuihui
String header = request.getHeader("req-name");
if ("yihuihui".equals(header)) {
return true;
}
log.info("Request header error: {}", header);
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
log.info("Done!);
response.setHeader("res"."postHandler");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
log.info("Recycling"); }}Copy the code
This interface defines three methods that fire callbacks at different times
1.1 preHandle
If true is returned, the interception can be executed. If true is returned, the interception can be executed. If false is returned, backward travel is not allowed
Therefore, it can be used for security verification, user identity processing and so on
Need special attention is that, in both interceptor/Filter, in the use of the Request in the Request flow, be alert, usually Request parameter flow reading is one-off, if implemented here a Request parameter logging output, the Request flow data read out, but didn’t write back again, lost will lead to Request parameters
1.2 postHandler
This is called back after the handler method is executed and before the view is rendered. In short, at this point, we can manipulate the ModelAndView, add information to it, and be parsed and rendered by the view
Of course, given the current tendency to separate the front and back ends, this is actually not used much anymore
1.3 afterCompletion
As the name implies, this method is executed after the entire request is completed, after the DispatcherServlet has rendered the corresponding view. This method is mainly used for resource cleaning
2. Register and test
Next let’s put our custom interceptor into effect
Implement the WebMvcConfigurer interface, override the addInterceptors method, realize the interceptor registration
@RestController
@SpringBootApplication
public class Application implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new SecurityInterceptor()).addPathPatterns("/ * *");
}
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
@GetMapping(path = "show")
public String show(a) {
returnUUID.randomUUID().toString(); }}Copy the code
3. Summary
This article has completed the missed SpringMVC interceptor knowledge, from the point of view of use, relatively simple, need to pay attention to the knowledge, nothing more than three interceptor timing
- PreHander: The controller method fires before execution and returns ture/false. Ture means pass
- PostHandler: Controller executes after the view is rendered before
- AfterCompletion: triggered afterCompletion
Second, compared with the filter, the interceptor in addition to operating requset/response, can also operate handler/modelAndView/exception
III. Can’t miss the source code and related knowledge
0. Project
- Project: github.com/liuyueyi/sp…
- Source: github.com/liuyueyi/sp…
1. Wechat official account: a gray Blog
The above content is not as good as the letter, purely the words of a family, due to the limited personal ability, there are inevitably omissions and mistakes, such as found bugs or better suggestions, welcome criticism and correction, not grudging gratitude
Below a gray personal blog, record all study and work in the blog, welcome everyone to visit
- A gray Blog personal Blog blog.hhui. Top
- A Gray Blog-Spring feature Blog Spring.hhui. Top