springboot 使用 servlet 过滤器
所属分类 springboot
浏览量 1217
import java.io.IOException;
import java.time.LocalDateTime;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class TimeLogFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("TimeLogFilter init,"+LocalDateTime.now());
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
long start = System.currentTimeMillis();
filterChain.doFilter(servletRequest,servletResponse);
long end = System.currentTimeMillis();
long time = end - start;
String url = ((HttpServletRequest)servletRequest).getServletPath();
System.out.println("TimeLogFilter."+time+","+url);
}
@Override
public void destroy() {
}
}
两种注册方式
FilterRegistrationBean
ServletComponentScan 注解
TimeLogFilter 使用 FilterRegistrationBean 注册
@Bean
public FilterRegistrationBean registFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new TimeLogFilter());
registration.addUrlPatterns("/*");
registration.setName("TimeLogFilter");
registration.setOrder(1);
return registration;
}
TimeLogFilter2 使用 ServletComponentScan 注解注册
@WebFilter(urlPatterns = "/*", filterName = "logFilter2")
public class TimeLogFilter2 implements Filter {
TimeLogFilter2 没有设置顺序
@WebFilter 注解并没有指定执行顺序的属性
Filter 顺序 建议 使用 FilterRegistrationBean order 来控制
order小的先执行
例子代码
https://gitee.com/dyyx/springboothello/tree/master/src/main/java/demo/filter
上一篇
下一篇
ORC文件格式
flink基础
装逼词汇大全
springboot 使用 拦截器
问题排查命令和工具及实战案例
maven-shade-plugin 使用指南