这篇文章将为大家详细讲解有关SpringBoot怎么整合Filter,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency>
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() { } }
@ServletComponentScan
@SpringBootApplication /*在SpringBoot启动时会扫描@WebServlet,@WebFilter注解,并将该类实例化*/ @ServletComponentScan public class SpringbootWebApplication { public static void main(String[] args) { SpringApplication.run(SpringbootWebApplication.class, args); } }
访问localhost:8080/first
进入First Filter First Servlet 离开First 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() { } }
/*Filter 配置类*/@Configurationpublic class FilterConfig {@Bean public FilterRegistrationBean getFilterRegistrationBean(){ FilterRegistrationBean bean = new FilterRegistrationBean(new SecondFilter());//bean.addUrlPatterns(new String[]{"*.do","*.jsp"}); bean.addUrlPatterns("/second");return bean; } }
访问 http://localhost:8080/second
进入SecondFilter Second Servlet 离开SecondFilter
关于SpringBoot怎么整合Filter就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。