1.通过注解扫描完成Filter组件的注册
1.1 编写Filter
package com.demo.filter; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import java.io.IOException; /** * springboot整合Filter方式一 * 以往在web.xml里面编写filter * <filter> * <filter-name>FirstFilter</filter-name> * <filter-class>com.demo.filter.FirstFilter</filter-class> * </filter> * * <filter-mapping> * <filtr-name>FirstFilter</filtr-name> * <url-pattern>/hello</url-pattern> * </filter-mapping> * * filter过滤器 */ //@WebFilter(filterName = "FirstFilter",urlPatterns ={"*.do","*.jsp"}) @WebFilter(filterName = "FirstFilter",urlPatterns = "/first") public class FirstFilter implements Filter { //doFilter一般是对request(请求)执行过滤操作 @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("进入Filter"); // 放行 chain.doFilter(request,response); System.out.println("离开Filter"); } @Override public void destroy() { } @Override public void init(FilterConfig filterConfig) throws ServletException { } }
1.2 编写启动类
/** * springBoot整合Filter 方式一 */ @SpringBootApplication @ServletComponentScan public class App { public static void main(String[] args) { SpringApplication.run(App.class,args); } }
1.3 启动main 在浏览器打开http://localhost:8080/forst
2.通过方法完成Filter组件的注册
2.1编写Filter
/** * springboot整合servlet方式二 */ public class SecondServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("SecondServlet..........."); } }
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注册方法
* @return
*/
@Bean
public FilterRegistrationBean getFilterRegistrationBean(){
FilterRegistrationBean bean=new FilterRegistrationBean(new SecondFilter());
// bean.addUrlPatterns(new String[]{"*.do",".jsp"});
bean.addUrlPatterns("/second");
return bean;
}
}
以下如上
小结:整合Filter有两种方式:1.注解:@WebFilter 2.方法:@SpringBootApplication SpringBootAppion.run(,) @Bean ServletRegistrationBean addUrlPattern FileRegisterationBean addUrlPatter