spring boot 加载外部filter方式
spring boot filter两种配置方式
1、自定义filter配置
spring mvc方式filter的配置方式就不用多说了,下面说一下spring boot的方式,由于springboot没有web.xml所以需要新增filter的配置类。下面是一个自定义的filter,实现了每次调用Controller打印自定义的filter的调用时长
import org.springframework.stereotype.Component;
import javax.servlet.*;
import java.io.IOException;
/**
* <br>
* 标题: 自定义filter <br>
* 描述: <br>
*
* @author shenxiangwei
* @time 2019/8/28 5:29 下午
*/
@Component
public class TestMyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("我的过滤器初始化");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
Long startTime = System.currentTimeMillis();
System.out.println("过滤器开始执行,时间"+System.currentTimeMillis());
filterChain.doFilter(servletRequest,servletResponse);
Long finishTime = System.currentTimeMillis();
System.out.println("过滤器耗时"+(finishTime-startTime));
}
@Override
public void destroy() {
System.out.println("我的过滤器销毁");
}
}
只需如上配置便实现了自定义的filter
2、加载外部jar包配置
我们可能会需要外部jar包的filter,把上面的作为jar包依赖到项目中,需要去掉@Component注解,同时在项目中假如配置类,如下:
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.ArrayList;
import java.util.List;
/**
* <br>
* 标题: TestMyFilterConfig <br>
* 描述: <br>
*
* @author shenxiangwei
* @time 2019/8/28 6:17 下午
*/
@Configuration
public class TestMyFilterConfig {
@Bean
public FilterRegistrationBean timeFilter(){
//创建 过滤器注册bean
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
TestMyFilter testMyFilter = new TestMyFilter();
registrationBean.setFilter(testMyFilter);
List urls = new ArrayList();
//给所有请求加过滤器
urls.add("/*");
//设置 有效url
registrationBean.setUrlPatterns(urls);
return registrationBean;
}
}
参考:https://www.jianshu.com/p/3960fd97a294?utm_source=oschina-app