@Slf4j
@Order(1)
@WebFilter(filterName = "myFilter", urlPatterns = {"/asyncResultGet/*"}, initParams = {@WebInitParam(name = "author", value = "Jaemon")})
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig)
throws ServletException {
// 得到过滤器的名字
log.info("过滤器初始化={}", filterConfig.getFilterName());
// 得到在web.xml文件中配置的初始化参数
String author = filterConfig.getInitParameter("author");
log.info("author={}", author);
// 返回过滤器的所有初始化参数的名字的枚举集合。
Enumeration<String> initParameterNames = filterConfig.getInitParameterNames();
log.info("是否存在初始化参数集={}", initParameterNames.hasMoreElements());
while (initParameterNames.hasMoreElements()) {
String paramName = initParameterNames.nextElement();
log.info("paramName={}", paramName);
}
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
// 对 request 和 response 进行一些预处理
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
log.info("execute before");
// 让目标资源执行,放行
filterChain.doFilter(request, response);
log.info("execute after");
}
@Override
public void destroy() {
log.info("过滤器销毁");
}
}
- @Order注解表示执行过滤顺序,值越小,越先执行
- filterName: 指定过滤器的 name 属性
- urlPatterns: 指定过滤的地址(不包含上下文)
- initParams: 指定过滤器初始化参数
注意: Application 入口中需要加入
@ServletComponentScan
注解
通过继承 Spring 的org.springframework.web.filter.OncePerRequestFilter
来实现过滤器
@Slf4j
@Component
public class MyFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
logger.info("过滤器执行");
filterChain.doFilter(request, response);
}
}