Servlet 3.1 api中@WebFilter实现过滤器

使用@WebFileter注解的过滤器,需要实现Filter接口,其定义如下:

public interface Filter {

    // 初始化
    public void init(FilterConfig filterConfig) throws ServletException;
	
    // 过滤方法	
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain)
            throws IOException, ServletException;
    
   // 销毁
    public void destroy();
}

以下是个过滤器的例子:

@WebFilter(urlPatterns = "/*")
public class MyFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(MyFilter.class);

    @Override
    public void init(FilterConfig filterConfig) {
        logger.warn("过滤器初始化:{}", filterConfig);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
        while (headerNames.hasMoreElements()) {

            String headerName = headerNames.nextElement();
            Enumeration<String> headers = httpServletRequest.getHeaders(headerName);
            while (headers.hasMoreElements()) {
                String headerValue = headers.nextElement();
                logger.warn("{}={}", headerName, headerValue);
            }
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        logger.warn("过滤器销毁:{}",this);
    }
}
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享