Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the SpringBoot interceptor

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Today, the editor will share with you the relevant knowledge points about how to use the SpringBoot interceptor. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.

HandlerInterceptor detailed explanation

HandlerInterceptor allows you to customize the workflow interface of the handler processor execution chain. We can customize the interceptor to intercept the handlers processor (you can understand it as the interface of the controller layer), so that you can add some common repetitive processing behavior (such as interface authentication, interface logging, performance monitoring, etc.) without having to modify the implementation of each handler.

Note that this is based on the SpringBoot 2.3.12.RELEASE version.

The HandlerInterceptor interface has only three default empty implementation methods, which in the lower version are not default methods, but abstract methods.

Public interface HandlerInterceptor {default boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {return true;} default void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, @ Nullable ModelAndView modelAndView) throws Exception {} default void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, @ Nullable Exception ex) throws Exception {}}

The execution sequence diagram of these three methods is as follows:

PreHandle

PreHandle pre-processing intercepts the execution of a processor (handler). The preHandle method is called after the HandlerMapping determines an appropriate processor object, but before the HandlerAdapter invokes the processor. It simply means that the controller interface is executed before it is called.

Intercepter is chained, which is executed one by one. If this method returns true, the next interceptor is executed or the processor is executed directly. If this method returns false or throws an exception, the execution chain is terminated and the handler is no longer called.

Note that postHandle and afterCompletion will not be executed if this method does not return true.

So what's the use of this method? In fact, you can do some preprocessing before the interface is called, such as user rights verification.

Package com.chenpi;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.lang.Nullable;import org.springframework.stereotype.Component;import org.springframework.web.method.HandlerMethod;import org.springframework.web.servlet.HandlerInterceptor / * * @ Description user rights verification block * @ Author tangerine peel * @ Date 2021-6-27 * @ Version 1.0 * / @ Componentpublic class UserPermissionInterceptor implements HandlerInterceptor {@ Override public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) {if (handler instanceof HandlerMethod) {HandlerMethod handlerMethod = (HandlerMethod) handler / / get user rights verification annotations UserAuthenticate userAuthenticate = handlerMethod.getMethod () .getAnnotation (UserAuthenticate.class); if (null = = userAuthenticate) {userAuthenticate = handlerMethod.getMethod () .getDeclaringClass () .getAnnotation (UserAuthenticate.class) } if (userAuthenticate! = null & & userAuthenticate.permission ()) {/ / verify user information UserContext userContext = userContextManager.getUserContext (request); if (null = = userContext) {return false;} return true;}} postHandle

PostHandle post processing is called after HandlerAdapter invokes the processor, but before DispatcherServlet renders the view. You can do some extra processing for ModelAndView here. It can be simply understood as execution after the controller interface is called.

Note that the execution order of this method in the execution chain is reversed, that is, the interceptor is declared first and then executed.

AfterCompletion

After the afterCompletion is completed, it is executed after the request has been processed, that is, after rendering the view. It is generally used to clean up some resources, cooperate with the execution time of preHandle computing interface, etc.

Note that, like postHandle, this method is executed in reverse order in the chain of execution, that is, the interceptor is declared first and then executed.

@ Overridepublic void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, @ Nullable Exception ex) {/ / clear the user information of the current thread after the request is completed, UserContextHolder.removeUserContext ();} register the interceptor

Note that our custom interceptor will not take effect until it is registered through the implementation class of WebMvcConfigurer.

Package com.yzj.ehr.common.config;import com.yzj.ehr.common.context.UserContextResolver;import org.springframework.stereotype.Component;import org.springframework.web.method.support.HandlerMethodArgumentResolver;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;import com.yzj.ehr.common.interceptor.UserPermissionInterceptor / * @ Description registered interceptor * @ Author tangerine peel * @ Date 2021-6-27 * @ Version 1.0 * / @ Componentpublic class WebAppConfigurer implements WebMvcConfigurer {private UserPermissionInterceptor userPermissionInterceptor; public WebAppConfigurer (final UserPermissionInterceptor userPermissionInterceptor) {this.userPermissionInterceptor = userPermissionInterceptor } @ Override public void addInterceptors (InterceptorRegistry registry) {/ / matches all interfaces, excluding the / base/test interface registry.addInterceptor (userPermissionInterceptor) .addPathPatterns ("/ * *") .origindePathPatterns ("/ base/test");}} that's all about the article "how to use the SpringBoot interceptor". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report