SpringBoot注册拦截器

实例

创建MyInterceptor

public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle");
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");

    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");

    }
}

创建WebMvcConfig

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptor()).addPathPatterns("/**");
    }
    @Bean
    MyInterceptor myInterceptor(){
        return new MyInterceptor();
    }
}

创建HelloController

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }
}

启动之后,控制台输出

preHandle
postHandle
afterCompletion
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 中注册拦截有两种方式:通过配置文件和通过注解。 1. 通过配置文件注册拦截 在 Spring Boot 的配置文件中配置拦截,可以使用 WebMvcConfigurer 接口中的 addInterceptors 方法注册拦截。例如: ```java @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**"); } } ``` 上面的代码中,MyInterceptor 是自定义的拦截类,addPathPatterns 用于配置拦截的路径。这里配置为“/**”,表示拦截所有的请求。 2. 通过注解注册拦截拦截类上添加 @Component 注解,然后在启动类中使用 @ServletComponentScan 注解扫描即可。例如: ```java @Component public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 拦截逻辑 } } ``` ```java @SpringBootApplication @ServletComponentScan public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 这里的 MyInterceptor 也是自定义的拦截类。 无论采用哪种方式,都需要实现 HandlerInterceptor 接口,并实现其中的 preHandle、postHandle 和 afterCompletion 方法,分别表示在请求处理前、请求处理后和请求处理完成后执行的逻辑。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值