SpringBoot——拦截器

本文详细介绍了在提供API时使用拦截器的重要性,特别是在进行接口安全性校验方面。通过创建自定义拦截器类和配置类,可以实现对请求前后的处理,包括安全性检查、日志记录等操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

拦截器

一、为什么需要使用拦截器

我们在提供 API 的时候,经常需要对 API 进行统一的拦截,比如进行接口的安全性校验。

二、如何进行拦截器设置

2.1、创建一个拦截器类:ApiInterceptor

@Component
public class ApiInterceptor implements HandlerInterceptor {
    //请求之前
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        System.out.println("进入拦截器");
        System.out.println(">>>MyInterceptor>>>>>>>在请求处理之前进行调用(Controller方法调用之前)");
        return true;
    }
    //请求时
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
		System.out.println(">>>MyInterceptor>>>>>>>请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)");
    }
    //请求完成
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
		System.out.println(">>>MyInterceptor>>>>>>>在整个请求结束之后被调用,也就是在DispatcherServlet");
        // 渲染了对应的视图之后执行(主要是用于进行资源清理工作)");
    }
}

2.1、定义拦截器配置类

@SpringBootConfiguration 注解的类继承 WebMvcConfigurationSupport 类,并重写 addInterceptors 方法,将 ApiInterceptor 拦截器类添加进去,代码如下:

@SpringBootConfiguration
public class WebConfig extends WebMvcConfigurationSupport{

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        //addPathPatterns 用于添加拦截规则
        //excludePathPatterns 用于排除拦截
        registry.addInterceptor(new ApiInterceptor());
        super.addInterceptors(registry);
    }
    /**
     * 配置静态资源
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        System.out.println("配置不拦截静态资源");
        //registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        super.addResourceHandlers(registry);
    }
}
  • 关注点:Action(部分Web请求)
  • 如何实现:Java反射机制(动态代理)
  • 应用场景:拦截未登录用户、审计日志
  • 是否依赖servlet容器:不依赖
  • Spring提供的支持:HandlerInterceptorAdapter类、HandlerInterceptor接口
  • 级别:非系统级
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值