上篇文章中说了SpringBoot中是如何使用servlet的,本文将讲解在SpringBoot中对过滤器Filter的实现
一.编写MyFilter实现Filter接口
package com.maxbill.core.webbox.filter;
import org.apache.log4j.Logger;
import javax.servlet.*; import javax.servlet.annotation.WebFilter; import java.io.IOException;
/** * @功能 自定义过滤器 * @作者 zuoshuai(MaxBill) * @日期 2017/7/6 * @时间 15:18 * @备注 MyFilter */ public class MyFilter implements Filter {
Logger log = Logger.getLogger(MyFilter.class);
@Override
public void init(FilterConfig config) throws ServletException {
log.info(">>>>>>>>>过滤器初始化>>>>>>>>>");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException { log.info(">>>>>>>>>执行过滤操作>>>>>>>>>"); chain.doFilter(request, response); }
@Override
public void destroy() {
log.info(">>>>>>>>>过滤器销毁>>>>>>>>>");
}
}
二.增加注解
1.过滤器增加@WebFilter注解,使能够被扫描到
@WebFilter(filterName = "myFilter", urlPatterns = "/*") public class MyFilter implements Filter {
Logger log = Logger.getLogger(MyFilter.class);
@Override
public void init(FilterConfig config) throws ServletException {
log.info(">>>>>>>>>过滤器初始化>>>>>>>>>");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException { log.info(">>>>>>>>>执行过滤操作>>>>>>>>>"); chain.doFilter(request, response); }
@Override
public void destroy() {
log.info(">>>>>>>>>过滤器销毁>>>>>>>>>");
}
}
2.启动类增加@ServletComponentScan注解,扫描项目中的filter
package com.maxbill;
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan;
@ServletComponentScan @SpringBootApplication public class MaxbillApplication {
public static void main(String\[\] args) {
SpringApplication.run(MaxbillApplication.class, args);
}
}
启动项目测试:
INFO com.maxbill.core.webbox.filter.MyFilter:23 - >>>>>>>>>过滤器初始化>>>>>>>>>
INFO com.maxbill.core.webbox.filter.MyFilter:29 - >>>>>>>>>执行过滤操作>>>>>>>>>