項目結構在(IDEA創建maven的spring boot項目,【極簡版】切面編程+swagger調用 )基礎上實現
1、攔截器
----src
--------main
--------|---java
--------|---|----com.demo
--------|---|---|---config
--------|---|---|---|----MyInterceptor
--------|---|---|---|----AppConfig
--------|---|---|---controller
--------|---|---|---|----TestController
--------|---|---|---|----DemoApplication
--------|---resources
--------|---|----application.yml
主要類:
1)攔截器操作類——攔截先後和操作
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 在請求處理之前執行的邏輯,返回true表示繼續執行請求處理,返回false表示中止請求處理 System.out.println("Pre-handle method is called"); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { // 在請求處理之後視圖渲染之前執行的邏輯 System.out.println("Post-handle method is called"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { // 在請求處理完成後執行的邏輯 System.out.println("After-completion method is called"); } }
2)攔截器配置類——攔截範圍【此處攔截所有接口】
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class AppConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { // 註冊自定義攔截器 registry.addInterceptor(new MyInterceptor()).addPathPatterns("/*"); } }
2、監聽器
----src
--------main
--------|---java
--------|---|----com.demo
--------|---|---|---config
--------|---|---|---|----MyApplicationListener
--------|---|---|---controller
--------|---|---|---|----TestController
--------|---|---|---|----DemoApplication
--------|---resources
--------|---|----application.yml
涉及的類:
1)MyApplicationListener——監聽到後執行的邏輯
import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; @Component public class MyApplicationListener implements ApplicationListener<ApplicationReadyEvent> { @Override public void onApplicationEvent(ApplicationReadyEvent event) { // 在應用程序啓動後執行的邏輯——打印一串文字 System.out.println("Application is ready to accept requests."); } }
2)觸發類——項目啓動後,最後一行打印上面類中的一行字
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication{ public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }