Spring中filter过滤器的定义方法
作者:L_J_X03
这篇文章主要介绍了Spring中filter过滤器的定义方法,Filter 程序是一个实现了特殊接口的 Java 类,与 Servlet 类似,也是由 Servlet 容器进行调用和执行的,需要的朋友可以参考下
filter
spring的filter是作用在interceptor(拦截器)之前,filter主要是依赖serlvet容器
filter怎样在spring中的使用
1.只用自定义的过滤器
使用WebFilter要使用ServletComponentScan注解,不然会失效
实现java.servlet.filter接口
import javax.servlet.*; import javax.servlet.annotation.WebFilter; import java.io.IOException; @Component @WebFilter(filterName="myFilter",urlPatterns = "/*") public class MyFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { filterChain.doFilter(servletRequest,servletResponse); } }
@SpringBootApplication @ComponentScan(value = "com.example") @ServletComponentScan //扫描过滤器 public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
继承springframework.web.filter.oncePerRequestFilter(同样是要使用@ServletComponentScan)
import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebFilter //继承OncePerRequestFilter的过滤的类,对每个请求只会过滤一次,这也是与实现Filter类不一样的地方 public class MyOnceProRequestFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException { filterChain.doFilter(httpServletRequest,httpServletResponse); } }
2.注册自己自定义的过滤器
写一个配置类(使用Configuration),使用@Bean注入
@Configuration //表示这是一个设置类 public class MyRegistration { @Bean public FilterRegistrationBean MyRegistrationBean(MyFilter myFilter){ FilterRegistrationBean<Filter> registrationBean = new FilterRegistrationBean<>(); registrationBean.setFilter(myFilter); //设置过滤器 registrationBean.setUrlPatterns(Collections.singleton("/*")); //设置过滤路径 registrationBean.setOrder(1); //设置优先级 return registrationBean; } }
到此这篇关于Spring中filter过滤器的定义方法的文章就介绍到这了,更多相关filter过滤器的定义内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!