本文最后更新于 1919 天前,其中的信息可能已经有所发展或是发生改变。
- 通过注解扫描完成 Filter 组件的注册
- 在servlet3.0之后,我们可以使用注解@WebFilter的方式进行配置过滤器,该方式过滤不用去xml文件中配置就可以使用,但是默认过滤器顺序是按照类名来控制,如果对过滤器顺序有严格的要求,则需要在web.xml中定义(按先后顺序)。
- 1.1 编写 Filter /***SpringBoot 整合 Filter 方式一
<filter> <filter-name>FirstFilter</filter-name> <filter-class>com.bjsxt.filter.FirstFilter</filter-class> </filter> <filter-mapping> <filter-name>FirstFilter</filter-name> <url-pattern>/first</url-pattern> </filter-mapping>//@WebFilter(filterName="FirstFilter",urlPatterns={"*.do","*.jsp"}) @WebFilter(filterName="FirstFilter",urlPatterns="/first") public class FirstFilter implements Filter { @Override public void destroy() { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { System.out.println("进入 Filter"); arg2.doFilter(arg0, arg1); System.out.println("离开 Filter"); } @Override public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub } }
- 1.2 编写启动类
/***SpringBoot 整合 Filter 方式一 **/ @SpringBootApplication @ServletComponentScan public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
- 通过方法完成 Filter 组件的注册
- 2.1 编写 Filter
/***SpringBoot 整合 Filter 方式二 **/ public class SecondFilter implements Filter { @Override public void destroy() { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { System.out.println("进入 SecondFilter"); arg2.doFilter(arg0, arg1); System.out.println("离开 SecondFilter"); } @Override public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub } }- 2.2 编写启动类
/*** SpringBoot 整合 Filter 方式二 ***/ @SpringBootApplication public class App2 { public static void main(String[] args) { SpringApplication.run(App2.class, args); } /*** 注册 Servlet * @return */ @Bean public ServletRegistrationBean getServletRegistrationBean(){ ServletRegistrationBean bean = new ServletRegistrationBean(new SecondServlet()); bean.addUrlMappings("/second"); return bean; } /*** 注册 Filter */ @Bean public FilterRegistrationBean getFilterRegistrationBean(){ FilterRegistrationBean bean = new FilterRegistrationBean(new SecondFilter()); //bean.addUrlPatterns(new String[]{"*.do","*.jsp"}); bean.addUrlPatterns("/second"); return bean; } }