时间:2020-11-19 17:48:35 | 栏目:JAVA代码 | 点击:次
前言
过滤器(Filter)是Servlet中常用的技术,可以实现用户在访问某个目标资源之前,对访问的请求和响应进行拦截,常用的场景有登录校验、权限控制、敏感词过滤等,下面介绍下Spring Boot配置过滤器的两种方式。
使用@WebFilter注解为声明当前类为filter,第一个参数为该filter起一个名字,第二个参数为说明要拦截的请求地址,当前类需要实现Filter接口,里面有三个方法,分别为过滤器初始化、过滤方法和过滤器销毁。
@Slf4j @WebFilter(filterName = "myFilter1", urlPatterns = "/*") public class MyFilter1 implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { log.info(filterConfig.getFilterName() + " init"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) { log.info("myFilter1 begin"); try { log.info("业务方法执行"); chain.doFilter(request, response); } catch (Exception e) { log.error("error!", e); } log.info("myFilter1 end"); } @Override public void destroy() { } }
启动类添加@ServletComponentScan注解,@ServletComponentScan注解所扫描的包路径必须包含该Filter,代码如下:
@SpringBootApplication @ServletComponentScan(basePackages = "com.example.demo.filter") public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
新建MyFilter2.java类,不要加注解@WebFilter,代码如下:
@Slf4j public class MyFilter2 implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { log.info(filterConfig.getFilterName() + " init"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) { log.info("myFilter2 begin"); try { log.info("业务方法执行"); chain.doFilter(request, response); } catch (Exception e) { log.error("error!", e); } log.info("myFilter2 end"); } @Override public void destroy() { } }
新建配置类WebConfig.java,配置bean,代码如下:
@Configuration public class WebConfig { @Bean public FilterRegistrationBean testFilterRegistration() { FilterRegistrationBean registration = new FilterRegistrationBean(new MyFilter2()); registration.addUrlPatterns("/test"); // registration.setName("myFilter2"); return registration; } }
项目启动后浏览器访问http://localhost:8080/test,可以看到过滤器已生效,后台打印日志如下:
[nio-8080-exec-1] com.example.demo.filter.MyFilter1 : myFilter1 begin
[nio-8080-exec-1] com.example.demo.filter.MyFilter1 : 业务方法执行
[nio-8080-exec-1] com.example.demo.filter.MyFilter1 : myFilter1 end
到此Spring Boot配置过滤器的两种方式已经全部实现,有问题欢迎留言沟通哦!
完整源码地址: https://github.com/suisui2019/springboot-study
总结