如何在SpringBoot中使用过滤器

x33g5p2x  于2021-11-27 转载在 Spring  
字(1.4k)|赞(0)|评价(0)|浏览(493)

一、注解方式

1.1、创建SpringBoot Web工程

1.2、创建Filter类并添加@WebFilter注解

@WebFilter(urlPatterns = "/filter")
public class MyFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("进入过滤器");
        chain.doFilter(request,response);
    }
}

1.3、在引导类上添加@ServletComponentScan注解

@SpringBootApplication
@ServletComponentScan
public class Ch07SpringbootFilterApplication {

    public static void main(String[] args) {
        SpringApplication.run(Ch07SpringbootFilterApplication.class, args);
    }
}

测试:

二、配置类方式

2.1、创建SpringBoot工程

2.2、创建Filter类

需要实现Filter接口并且重写doFilter方法

public class MyFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("进入使用配置器类的过滤器");
        chain.doFilter(request,response);
    }
}

2.3、创建Filter配置类

@Configuration
public class FilterConfig {
    @Bean
    public FilterRegistrationBean myFilterRegistrationBean(){
        FilterRegistrationBean frb = new FilterRegistrationBean(new MyFilter());
        //添加要过滤的路径
        frb.addUrlPatterns("/user/filter/*");
        return frb;
    }
}

2.4、编写Controller类

@Controller
@RequestMapping("/user")
public class MyController {
    @RequestMapping("/filter/1")
    public @ResponseBody String filter(){
        return "filter";
    }
    @RequestMapping("/other")
    public @ResponseBody String other(){
        return "other";
    }
}

测试:

首先测试没有添加过滤器的请求

控制台没有打印任何信息
然后测试添加了过滤器的请求

执行了在过滤器内的代码,测试成功

相关文章