拦截器与过滤器的区别 :
- 拦截器是基于java的反射机制的,而过滤器是基于函数回调。
- 拦截器不依赖与servlet容器,过滤器依赖与servlet容器。
- 拦截器只能对action请求起作用,而过滤器则可以对几乎所有的请求起作用。
- 拦截器可以访问action上下文、值栈里的对象,而过滤器不能访问。
- 在action的生命周期中,拦截器可以多次被调用,而过滤器只能在容器初始化时被调用一次拦截器的代
码实现。 - Filter基于回调函数,我们需要实现的filter接口中doFilter方法就是回调函数,而interceptor则基于
java本身的反射机制,这是两者最本质的区别。 - Filter是依赖于servlet容器的,即只能在servlet容器中执行,很显然没有servlet容器就无法来回调
doFilter方法。而interceptor与servlet容器无关。 - Filter的过滤范围比Interceptor大,Filter除了过滤请求外通过通配符可以保护页面,图片,文件等等,
而Interceptor只能过滤请求。 - Filter的过滤例外一般是在加载的时候在init方法声明,而Interceptor可以通过声明是guest请求还
是user请求来辨别是否过滤。
一.过滤器
1.不使用springSecurity时,添加过滤器在启动类中增加
MyFilter需继承Filter
@Bean public FilterRegistrationBean myFilter(){ FilterRegistrationBean registrationBean=new FilterRegistrationBean(); FilterRegistrationBean.setName("myFilter"); MyFilter mf=new MyFilter(); //spring boot 会按照order值的大小,从小到大的顺序来依次过滤 registrationBean.setOrder(0); registration.addUrlPatterns("/*"); return registration; }
使用springSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter{ @Override protected void configure(HttpSecurity httpSecurity) throws Exception { //退出访问/logout时,执行logoutSuccessHandler这个处理器 httpSecurity.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler); //添加过滤器,先执行AFilter,再执行authenticationTokenFilter httpSecurity.addFilterBefore(authenticationTokenFilter, AFilter.class); } }
得继承OncePerRequestFilter
@Component
@Order(1)//指定执行顺序
public JwtAuthenticationTokenFilter extends OncePerRequestFilter
二:拦截器
拦截器,在AOP(Aspect-Oriented Programming)中用于在某个方法或字段被访问之前,进行拦截然后在之前或之后加入某些操作。拦截是AOP的一种实现策略
1.一般使用
MyInterceptor需继承HandlerInterceptor
@Configuration public class MyMvcConfigurer implements WebMvcConfigurer{ @Override public void addInterceptors(InterceptorRegistry registry){ //添加自定义拦截器 MyInterceptor mi=new MyInterceptor(); InterceptorRegistration i=registry.addInterceptor(mi); //拦截哪些路径 i.addPathPatterns(new String[]{"/**"}); //不拦截哪些路径 i.excludePathPatterns(new String[]{"/a"}); } }
2.在后端数据返回到前端时做一些处理
@ControllerAdvice public class MRSBA implements ResponseBodyAdvice{ @Override //obj为返回的数据 mt为数据格式类型 public Object beforeBodyWrite(Object obj,MethodParameter param,,MediaType mt,Class converter,ServerHttpRequest httpRequest,ServerHttpResponse httpResponse){ //具体业务逻辑 } }
热门文章
- 「3月4日」最高速度21.6M/S,2025年V2ray/Clash/SSR/Shadowrocket每天更新免费节点订阅链接
- 动物医院取什么名字好听一点(动物医院牌子)
- 「1月28日」最高速度19.3M/S,2025年SSR/Clash/V2ray/Shadowrocket每天更新免费节点订阅链接
- 中国饲料排名第一(中国饲料排名第一的企业)
- 宠物买卖纠纷找哪个部门协调解决 宠物买卖纠纷找哪个部门协调解决呢
- 宠物粮加工设备一套得多少钱 宠物粮食加工厂设备
- 「2月7日」最高速度22.9M/S,2025年V2ray/Clash/Shadowrocket/SSR每天更新免费节点订阅链接
- Java两个List<T> 求交集,差集,并集,去重后的并集_java
- 「1月9日」最高速度20.2M/S,2025年V2ray/Shadowrocket/SSR/Clash每天更新免费节点订阅链接
- 被小猫抓了多久过安全期(被小猫抓了多久会发病)