SpringBoot -- Interceptor拦截器如何配置&生效

1、新建拦截器 -- 例:

        新建一个LoginInterceptor拦截器实现implements HandlerInterceptor,导入spring-boot-                                                      starter-web,复写HandlerInterceptor里面的preHandle方法

2、新建一个配置类 -- 例:

        新建配置类想要生效就需要加上@Component注解

        新建配置类实现WebMVCConfigurer,实现里面的AddInterceptors方法,然后通过参数registry进行addInterceptor,这里new 一个自己创建的LoginInterceptor

        然后可以addPathPatterns,过滤所有请求("/**") 

        排除路径 -- excludePathPatterns("js/**") 排除静态资源路径

        

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
配置自定义拦截器拦截指定目录的 mapper 文件,可以按照以下步骤进行: 1. 创建一个自定义拦截器类,实现 MybatisInterceptor 接口,重写其中的 intercept() 方法,在该方法中实现自定义的拦截逻辑。 2. 在该拦截器类上使用 @Intercepts 注解定义需要拦截的方法以及拦截的时机,例如: ```java @Intercepts({ @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}), @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}) }) public class MyInterceptor implements Interceptor { // ... } ``` 以上示例中,定义了拦截 Executor 类中的 query() 和 update() 方法,并传入了对应的参数类型。 3. 在 Mybatis配置文件中,将该拦截器类添加到插件列表中,并指定需要拦截的 mapper 文件路径,例如: ```xml <configuration> <plugins> <plugin interceptor="com.example.MyInterceptor"> <property name="mapperPath" value="com/example/mapper/**/*Mapper.xml"/> </plugin> </plugins> </configuration> ``` 以上示例中,将 MyInterceptor 添加到插件列表中,并指定需要拦截的 mapper 文件路径为 com/example/mapper/ 目录下的所有 Mapper.xml 文件。 在 MyInterceptor 类中,可以通过获取配置文件中的 mapperPath 属性来获取需要拦截的 mapper 文件路径,然后根据该路径判断是否需要拦截当前执行的方法。 ```java public class MyInterceptor implements Interceptor { private String mapperPath; @Override public Object intercept(Invocation invocation) throws Throwable { MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0]; String mapperId = mappedStatement.getId(); if (mapperId.matches(mapperPath)) { // 需要拦截的方法 } return invocation.proceed(); } @Override public Object plugin(Object target) { return Plugin.wrap(target, this); } @Override public void setProperties(Properties properties) { mapperPath = properties.getProperty("mapperPath"); } } ``` 以上示例中,通过获取配置文件中的 mapperPath 属性,并使用正则表达式判断当前执行的方法是否需要拦截。如果需要拦截,则执行自定义的拦截逻辑。否则,直接调用被拦截方法的原始逻辑。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值