【SpringBoot中实现过滤器和拦截器】
1.过滤器和拦截器简述
过滤器Filter和拦截器Interceptor,在功能方面很类似,但在具体实现方面差距还是比较大的。
2.过滤器的配置
2.1 自定义过滤器,实现Filter接口(SpringBoot 3.0 开始,jakarta.servlet.Filter,jdk需要升级到17)
2.2 重写doFilter,实现过滤逻辑,酌情放行
2.3 创建注解,实现过滤的范围配置
3.拦截器的配置
3.1 自定义拦截器,实现HandlerInterceptor接口
3.2 实现接口中的拦截方法(preHandle-请求执行前、postHandler-请求执行后、aftercompletion-视图渲染后)
3.3 创建配置类,实现WebMvcConfigurer接口,重写addInterceptors方法
4.总结
4.1 Filter依赖于Servlet容器,属于Servlet规范的一部分,而Interceptor依赖于SpringMVC框架;【所依赖框架】
4.2 Filter的生命周期由servlet容器管理,而Interceptor通过IOC容器来管理,可通过注入等方式来获取其Bean的实例;【管理的容器】
4.3 Filter可拦截所有web资源(包括]sp,Servlet,静态资源),而Interceptor则只拦截controller。【拦截范围】
代码
1、过滤器:
javascript">@RestController
public class MyController {@GetMapping("/filter")public String filter() {return "filter";}
}
javascript">package com.example.demos.web.filter;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Objects;
/*** @date 2025/1/5 18:06* @description ip 请求的次数*/
@Component
//所有请求都会经过这个过滤器
@WebFilter(urlPatterns = "/*")
public class MyFilter implements Filter {@Overridepublic void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest) servletRequest;// 获取请求的ipString ip = request.getRemoteAddr();HttpSession session = request.getSession();Integer count = (Integer) session.getAttribute("count");count=Objects.isNull(count)?1:++count;System.out.println("ip:"+ip+" count:"+count);session.setAttribute("count", count);//放行filterChain.doFilter(servletRequest, servletResponse);}
}
结果:
2、拦截器
javascript">@RestController
public class MyController {@GetMapping("/interceptor")public String filter() {return "interceptor";}
}
进行拦截处理
javascript">public class MyHandlerInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {// 获取请求的ipString ip = request.getRemoteAddr();HttpSession session = request.getSession();Integer count = (Integer) session.getAttribute("count");count= Objects.isNull(count)?1:++count;System.out.println("ip:"+ip+" count:"+count);session.setAttribute("count", count);//放行return true;}
}
配置文件需要将自定义拦截器进行注册
javascript">@Configuration
public class InterceptorConfiguration implements WebMvcConfigurer {@Overridepublic void addInterceptors(InterceptorRegistry registry) {MyHandlerInterceptor interceptor = new MyHandlerInterceptor();//拦截所有请求registry.addInterceptor(interceptor).addPathPatterns("/**");}
}
结果: