SpringBoot 整合Filter
一、创建基础SpringBoot项目,集成Web即可
<**dependency**> <**groupId**>org.springframework.boot</**groupId**> <**artifactId**>spring-boot-starter-web</**artifactId**> </**dependency**>
二、方式一:通过注解方式注入
1. 创建Filter组件
com.zhl.springbootweb.filter.FirstFilter
- urlPatterns 可以指定后缀 或者 URL
- 实现@WebFilter注解
- 集成javax.servlet中的 Filter
package com.zhl.springbootweb.filter;
import javax.servlet.*; import javax.servlet.annotation.WebFilter; import java.io.IOException;
/*整合__Filter__方式一*/ //@WebFilter(filterName = "first Filter",urlPatterns = {"*.do","*.jsp"}) @WebFilter(filterName = "first Filter",urlPatterns = {"/first"}) public class FirstFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println(**"进入First Filter"); _/*放行*/ _ filterChain.doFilter(servletRequest,servletResponse); System.out.println("离开First Filter"**);
}
@Override
public void destroy() {
}
}
2. 启动类需要添加注解
@ServletComponentScan
@SpringBootApplication
/*在SpringBoot启动时会扫描@WebServlet,@WebFilter注解,并将该类实例化*/
@ServletComponentScan
public class SpringbootWebApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootWebApplication.class, args);
}
}
3.测试
访问localhost:8080/first
进入First Filter
First Servlet
离开First Filter
三、方式二:使用方法注入
1. 创建Filter
com.zhl.springbootweb.filter.SecondFilter
package com.zhl.springbootweb.filter;
import javax.servlet.*; import java.io.IOException; /* * 整合__Filter 方式二 * */ public class SecondFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println(**"进入SecondFilter"); _/*放行*/ _ filterChain.doFilter(servletRequest,servletResponse); System.out.println("离开SecondFilter"**);
}
@Override
public void destroy() {
}
}
2.创建配置类
/*Filter 配置类*/ @Configuration public class FilterConfig { @Bean public FilterRegistrationBean getFilterRegistrationBean(){ FilterRegistrationBean bean = new FilterRegistrationBean(new SecondFilter()); _//bean.addUrlPatterns(new String[]{"*.do","*.jsp"}); _ bean.addUrlPatterns("/second"); return bean; } }
3.测试
访问 http://localhost:8080/second
进入SecondFilter
Second Servlet
离开SecondFilter