过滤器:当你有一对东西的时候,你只希望选择符合你要求的某些东西,定义这些要求的工具就是过滤器
拦截器:在一个流程正在进行的时候 你希望干预它的进展,甚至终止他的进行 这就是拦截器做的事情
拦截器可以获取Spring中的个中Bean 而过滤器不行 拦截器归spring管理

过滤器

方式一

  1. //1.创建配置类
  2. @Configuration
  3. public class FilterConfig {
  4. //创建一个方法 用于注册过滤器
  5. @Bean
  6. public FilterRegistrationBean<CustomFilter> filterRegistrationBean() {
  7. FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
  8. //添加过滤器
  9. filterRegistrationBean.setFilter(new CustomFilter());
  10. //过滤规则 ---> 过滤所有请求
  11. filterRegistrationBean.addUrlPatterns("/*");
  12. // filterRegistrationBean.setOrder(1); 设置优先级 越小优先级越高
  13. return filterRegistrationBean;
  14. }
  15. }
  16. //2.创建类继承implements Filter
  17. public class CustomFilter implements Filter {
  18. @Override
  19. public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  20. System.out.println("我过滤了");
  21. chain.doFilter(request,response);//放行
  22. }
  23. }
  24. //3.测试
  25. @GetMapping("hello")
  26. public String hello() {
  27. return "success";
  28. }

方式二

  1. //通过注解的方式
  2. 1.在实现Filter的类上添加一个@WebFilter注解 fulterName 起一个名字 urlPatterns设置过滤规则
  3. @WebFilter(filterName = "customfilter",urlPatterns = {"/*"})
  4. public class CustomFilter implements Filter {
  5. @Override
  6. public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  7. System.out.println("我过滤了");
  8. chain.doFilter(request,response);
  9. }
  10. }
  11. 2.在启动类上添加一个@ServletComponentScan注解用于扫描过滤器
  12. @SpringBootApplication
  13. @ServletComponentScan
  14. public class SpringApplication10 {
  15. public static void main(String[] args) {
  16. SpringApplication.run(SpringApplication10.class, args);
  17. }
  18. }

拦截器使用

  1. 1.创建一个类 实现 HandlerInter
  2. @Service
  3. public class CustomInterceptor implements HandlerInterceptor {
  4. @Override
  5. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  6. System.out.println("执行之前");
  7. return true;
  8. }
  9. @Override
  10. public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
  11. System.out.println("执行之中");
  12. }
  13. @Override
  14. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
  15. System.out.println("执行之后");
  16. }
  17. 2. 创建一个配置类 实现WebMvcConfigurer 重写里面的 addInterceptors方法
  18. @Configuration
  19. public class InterceptorConfig implements WebMvcConfigurer {
  20. //将自定义拦截类注入进来
  21. @Autowired
  22. CustomInterceptor customInterceptor;
  23. @Override
  24. public void addInterceptors(InterceptorRegistry registry) {
  25. //将自定义拦截器添加进去 并配置拦截规则----->/** 拦截全部
  26. registry.addInterceptor(customInterceptor).addPathPatterns("/**");
  27. }
  28. }