In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "the creation method of three kinds of interceptors in Spring Boot". In the daily operation, I believe that many people have doubts about the creation methods of three kinds of interceptors in Spring Boot. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "the creation methods of three kinds of interceptors in Spring Boot". Next, please follow the editor to study!
Interceptor in Spring
Interceptors are a frequently used feature in web development. It can help us verify whether to log in, authorization, data verification, preset data and the efficiency of statistical methods, and so on. Today we will talk in more detail about interceptors in spring. There are two main kinds of interceptors in spring, one is HandlerInterceptor and the other is MethodInterceptor.
1. HandlerInterceptor interceptor
HandlerInterceptor is the interceptor in the springMVC project. It intercepts the address of the request and executes it before MethodInterceptor. Implementing an HandlerInterceptor interceptor can either implement the HandlerInterceptor interface directly or inherit the HandlerInterceptorAdapter class. The two methods go the same way. In fact, HandlerInterceptorAdapter declares the default implementation of all methods in the HandlerInterceptor interface, and we only need to rewrite the necessary methods after inheriting him. Here is the code for HandlerInterceptorAdapter. You can see that one method simply returns true by default, and the other two are empty methods:
/ * * Custom interceptor-based on the interceptor in the springmvc * @ ClassName: CustomInterceptor * @ Description: springMVC project, which intercepts the requested address and executes before MethodInterceptor. * the interceptor can only filter action requests. SPring allows multiple interceptors to exist at the same time and is managed through the interceptor chain. * when preHandle return true, execute the next interceptor until all interceptors are finished, and then run the intercepted request. * when preHandle return false, subsequent interceptor chains and intercepted requests are no longer executed. * @ author OnlyMate * @ Date 2:30:22 * * / public class CustomInterceptor implements HandlerInterceptor {@ Override public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {/ / TODO Auto-generated method stub return HandlerInterceptor.super.preHandle (request, response, handler) @ Override public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {/ / TODO Auto-generated method stub HandlerInterceptor.super.postHandle (request, response, handler, modelAndView);} @ Override public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {/ / TODO Auto-generated method stub HandlerInterceptor.super.afterCompletion (request, response, handler, ex);}}
What are these three methods for, what are their functions, when are they called, and what is the order of calls between different interceptors? You have to refer to DispatcherServlet's doDispatch method.
Protected void doDispatch (HttpServletRequest request, HttpServletResponse response) throws Exception {HttpServletRequest processedRequest = request; HandlerExecutionChain mappedHandler = null; boolean multipartRequestParsed = false; WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager (request); try {ModelAndView mv = null; Exception dispatchException = null; try {processedRequest = checkMultipart (request); multipartRequestParsed = (processedRequest! = request) / / Determine handler for the current request. MappedHandler = getHandler (processedRequest); if (mappedHandler = = null) {noHandlerFound (processedRequest, response); return;} / / Determine handler adapter for the current request. HandlerAdapter ha = getHandlerAdapter (mappedHandler.getHandler ()); / / Process last-modified header, if supported by the handler. String method = request.getMethod (); boolean isGet = "GET" .equals (method); if (isGet | | "HEAD" .equals (method)) {long lastModified = ha.getLastModified (request, mappedHandler.getHandler ()) If (logger.isDebugEnabled ()) {logger.debug ("Last-Modified value for [" + getRequestUri (request) + "] is:" + lastModified);} if (new ServletWebRequest (request, response) .checkNotModified (lastModified) & & isGet) {return }} if (! mappedHandler.applyPreHandle (processedRequest, response)) {return;} / / Actually invoke the handler. Mv = ha.handle (processedRequest, response, mappedHandler.getHandler ()); if (asyncManager.isConcurrentHandlingStarted ()) {return;} applyDefaultViewName (processedRequest, mv); mappedHandler.applyPostHandle (processedRequest, response, mv);} catch (Exception ex) {dispatchException = ex } catch (Throwable err) {/ / As of 4.3, we're processing Errors thrown from handler methods as well, / / making them available for @ ExceptionHandler methods and other scenarios. DispatchException = new NestedServletException ("Handler dispatch failed", err);} processDispatchResult (processedRequest, response, mappedHandler, mv, dispatchException);} catch (Exception ex) {triggerAfterCompletion (processedRequest, response, mappedHandler, ex);} catch (Throwable err) {triggerAfterCompletion (processedRequest, response, mappedHandler, new NestedServletException ("Handler processing failed", err)) } finally {if (asyncManager.isConcurrentHandlingStarted ()) {/ / Instead of postHandle and afterCompletion if (mappedHandler! = null) {mappedHandler.applyAfterConcurrentHandlingStarted (processedRequest, response);}} else {/ / Clean up any resources used by a multipart request. If (multipartRequestParsed) {cleanupMultipart (processedRequest);}}
The code is a bit long, but it encapsulates the entire process of springMVC processing the request. First, find the corresponding HandlerExecutionChain according to the request, which contains the handler for processing the request and all HandlerInterceptor interceptors; then call the preHandle method of each HandlerInterceptor interceptor before calling hander. If one interceptor returns false, the triggerAfterCompletion method is called and immediately returns no further execution; if all interceptors return true and no exception occurs, calling handler returns the ModelAndView object The postHandle method of each interceptor is then called separately; finally, the triggerAfterCompletion method is executed even if the previous step throws an exception. So much for the interceptor, let's take a look at what triggerAfterCompletion does
Private void triggerAfterCompletion (HttpServletRequest request, HttpServletResponse response, @ Nullable HandlerExecutionChain mappedHandler, Exception ex) throws Exception {if (mappedHandler! = null) {mappedHandler.triggerAfterCompletion (request, response, ex);} throw ex;}
According to the above code, analyze the execution order of different interceptors and their methods. Suppose there are five interceptors numbered 12345 respectively, and if everything is normal, the order of execution of the method is the afterCompletion of preHandle,54321 's postHandle,54321 of 12345. If the preHandle method of the interceptor numbered 3 returns false or throws an exception, the afterCompletion method of 21 will be executed next. The important thing to note here is that we should be careful to handle exceptions in preHandle when writing an interceptor, because once an exception is thrown, it will no longer be controlled by the interceptor. After the preHandle method of 12345 has been executed, if there is an exception in handler or an exception in the postHandle method of an interceptor, then the afterCompletion method of 54321 will be executed next, because as long as the preHandle method of 12345 is finished, the interceptor of the current interceptor will be recorded as an interceptor numbered 5, and afterCompletion will always execute backward from the current interceptor. Another way to implement the HandlerInterceptor interceptor is to implement the WebRequestInterceptor interface. In fact, it is the same as the two methods just now, and it is finally adapted into HandlerInterceptor by spring. One difference is that its preHandle method ends up returning only true.
Here, you can write your own business processing logic in the corresponding method according to your needs.
/ * * Custom interceptor-based on the interceptor in the springmvc * @ ClassName: CustomInterceptor * @ Description: springMVC project, which intercepts the requested address and executes before MethodInterceptor. * the interceptor can only filter action requests. SPring allows multiple interceptors to exist at the same time and is managed through the interceptor chain. * when preHandle return true, execute the next interceptor until all interceptors are finished, and then run the intercepted request. * when preHandle return false, subsequent interceptor chains and intercepted requests are no longer executed. * @ author OnlyMate * @ Date 2:30:22 28th August 2018 * * / public class CustomInterceptor implements HandlerInterceptor {private Logger logger = LoggerFactory.getLogger (CustomInterceptor.class) / * is executed before request processing, and is mainly used for permission verification, parameter filtering, etc. * / @ Override public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {logger.info ("CustomInterceptor = = > preHandle method: do request before"); return true } / * the current request is executed after processing, and is mainly used for logging, permission checking, performance monitoring, common behavior, etc. * / @ Override public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {logger.info ("CustomInterceptor = = > postHandle method: do request after") } / * when the return value of the perHandle method of the corresponding interceptor is true, postHandle execution is completed and the page is rendered, which is mainly used for resource cleaning work * / @ Override public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {logger.info ("CustomInterceptor = > afterCompletion method: do request finshed");}}
The configuration is as follows:
/ * * Web MVC configuration Adapter * @ ClassName: WebAppConfigurer * @ Description: * @ author OnlyMate * @ Date 2:39:31 on August 28th 2018 * * WebAppConfigurer extends WebMvcConfigurerAdapter is out of date in the Spring Boot2.0 version Replace * * / @ Configurationpublic class WebAppConfigurer implements WebMvcConfigurer {/ * inject custom interceptor * @ Title: addInterceptors * @ Description with the new class mentioned on the official website: the interceptor that comes first add will be more outward. The closer you get to the browser * @ Date * 2:47:28 * @ author OnlyMate * @ param registry * / @ Override public void addInterceptors (InterceptorRegistry registry) {WebMvcConfigurer.super.addInterceptors (registry) Registry.addInterceptor (new CustomInterceptor ()) .addPathPatterns ("/ * *"); / / intercept all requests}} II. MethodInterceptor interceptor
MethodInterceptor is an interceptor in an AOP project that intercepts methods, even if not methods in controller. There are also two ways to implement MethodInterceptor interceptors, one is to implement the MethodInterceptor interface, and the other is to use AspectJ annotations or configurations.
1. Implement the MethodInterceptor interface / * custom interceptor-method interceptor, which is based on the interceptor in the spring aop * @ ClassName: CustomMethodInterceptor * @ Description: AOP project, which intercepts the method * configured in applicationContext.xml * @ author OnlyMate * @ Date 3:35:24 on August 29th, 2018 * * / public class CustomMethodInterceptor implements MethodInterceptor {private Logger logger = LoggerFactory.getLogger (CustomMethodInterceptor.class) Override public Object invoke (MethodInvocation invocation) throws Throwable {logger.info ("CustomMethodInterceptor = = > invoke method: process method name is {}", invocation.getMethod () .getName ()); / / TODO processing operation return invocation.proceed ();}}
Configuration description
CustomAnnotation Custom comments
/ * Custom annotation object * @ ClassName: TableSplit * @ Description: TODO * @ author OnlyMate * @ Date 11:43:57 * * / @ Target (ElementType.METHOD) @ Retention (RetentionPolicy.RUNTIME) public @ interface CustomAnnotation {/ * * intercept method name description * / String name () default "; / * encryption * / String [] encrypt () default {} / * * decryption * / String [] decrypt () default {} 2. Use AspectJ annotation or configuration a, AspectJ-based note / * custom interceptor-method interceptor, annotation-based AspectJ method * @ ClassName: CustomAutoAspectJInterceptor * @ Description: configured in applicationContext.xml * @ author OnlyMate * @ Date 4:03:49 * / @ Component@Aspectpublic class CustomAutoAspectJInterceptor {private Logger logger = LoggerFactory.getLogger (CustomAutoAspectJInterceptor.class) @ Around ("execution (* com.onlymate.springboot.controller.*.* (..)") Public Object around (ProceedingJoinPoint point) throws Throwable {logger.info ("CustomAutoAspectJInterceptor = = > invoke method: process method class is {}", point.getTarget () .getClass ()); / / TODO processing operation return point.proceed () } b. Based on AspectJ configuration / * Custom interceptor-method interceptor, based on AspectJ mode * @ ClassName: CustomAspectJInterceptor * @ Description: configured in applicationContext.xml * @ author OnlyMate * @ Date 4:03:49 * * / public class CustomAspectJInterceptor {private Logger logger = LoggerFactory.getLogger (CustomAspectJInterceptor.class) Public Object around (ProceedingJoinPoint point) throws Throwable {logger.info ("CustomAspectJInterceptor = = > invoke method: process method class is {}", point.getTarget (). GetClass ()); / / TODO processing operation return point.proceed ();}} c, configuration instructions 3, effect diagram
IV. Talk about differences
The above two interceptors can have the effect of interception, but they intercept different targets and achieve different mechanisms, so sometimes they are suitable for different scenarios. HandlerInterceptoer intercepts the request address, so it is appropriate to do some verification, preprocessing and other operations for the request address. MethodInterceptor will not be easy to do when you need to count the response time of a request, because it may span many methods or involve only part of the code in a method that has already been defined. MethodInterceptor uses the implementation mechanism of AOP. In this article, it only describes how to use it, and there is little introduction about the principle and mechanism, because a considerable part of AOP is needed to be clear. There is nothing you can do to intercept HandlerInterceptoer on some common methods, so you can only use AOP's MethodInterceptor at this time. Using MethodInterceptor, you can easily implement a log interception process. In addition, there is something similar to the interceptor-Filter. Filter is specified by the Servlet specification, does not belong to the spring framework, and is also used to intercept requests. But it is suitable for coarse-grained interception, doing some codec processing, logging and so on before and after the request. Interceptors can provide finer-grained, more flexible solutions for certain requests and combinations of certain methods.
At this point, the study of "how to create three interceptors in Spring Boot" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.