IDEA创建maven的spring boot项目,【极简版】监听器+拦截器
项目结构在(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); } }