SpringBoot中拦截器Interceptor详解
前言
最近做微服务鉴权的时候,出现点问题,发现直接使用SpringSecurity不太好使。于是想自己使用拦截器来鉴权,但是又不知道咋用,写个博客记录一下吧。
一、拦截器配置
新建一个类实现HandlerInterceptor接口
先看看这个接口的源码
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package org.springframework.web.servlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.lang.Nullable;
public interface HandlerInterceptor {
// controller执行前 拦截
default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return true;
}
// controller执行后 页面渲染前 执行
default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
}
// 页面渲染完成后拦截
default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
}
}
我们自己写的代码
/**
* @author Lurious
* @version 1.0
* @date 2021/3/19 8:57
*/
@Component
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
}
}
把HandlerInterceptor中的方法复制过来 把 default改为public。
注意一定要把他放到 类加载容器中,即添加@Component注解。
二、在配置中加入拦截器(一定不要忘记)
1、实现WebMvcConfigurer方法
/**
* @author Lurious
* @version 1.0
* @date 2021/3/19 9:08
*/
@Configuration
public class MyConfig implements WebMvcConfigurer {
@Autowired
MyInterceptor myInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor);
}
}
注意: 一定注意整个项目中只能够实现一个WebMvcConfig 否则会有一个失效。
还有一定注意要把配置添加到容器中,即@Configuration注解。
此时一般情况下拦截器就生效了,可以进行一些鉴权操作。
但是其实我在配置的时候还是出现了问题,拦截器没有生效。
如果生效那就可以跳过了哈~
三、配置组件包扫描
为了解决拦截器不生效,其实就是没有放到容器中去。在启动类上加上@ComponentScan(value=“com.lcurious.*”) 注解,强行设置组件包扫描路径,就可以解决了。
@SpringBootApplication
@ComponentScan(value = "com.lcurious.*")
public class InterceptorTestApplication {
public static void main(String[] args) {
SpringApplication.run(RedistestApplication.class, args);
}
}