目的:研究spring boot 2.X攔截器的實現原理,並編寫本身的攔截器java
攔截器須要內容:web
一、自定義註解spring
二、自定義攔截器mvc
三、攔截器配置注入ide
實現代碼ui
① 自定義註解.net
@Target 註解做用域:類、方法等blog
@Retention 用來修飾註解,是註解的註解,標誌註解的生命週期繼承
package com.example.myproject.annotion; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface IntercepterRequired { }
②自定義攔截器生命週期
說明:自定義註解,繼承HandlerInterceptorAdapter ,重寫preHandle方法(請求方法前),具體攔截器的執行流程不明白的,你們在查查資料。
package com.example.myproject.intercepter; import com.example.myproject.annotion.IntercepterRequired; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.lang.reflect.Method; public class MyInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (! (handler instanceof HandlerMethod)){ return true; } HandlerMethod handlerMethod = (HandlerMethod)handler; Method method = handlerMethod.getMethod(); IntercepterRequired annotation = method.getAnnotation(IntercepterRequired.class); if (null != annotation) { System.out.println("我真的攔截到了。。。。。。。。。。。"); return true; } return true; } }
③ 攔截器配置注入
@Configuration 把配置文件注入容器中
@EnableWebMvc,是mvc的攔截器生效,若是缺乏此配置,自定義攔截器不生效
package com.example.myproject.config; import com.example.myproject.intercepter.MyInterceptor; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration @EnableWebMvc public class IntercepterConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**"); } }
用例: