Servlet Filter for HTTP


A problem of Filter is that the doChain method is for ServletRequest and ServletResponse.

public class MyFilter implements Filter {

    @Override
    public void init(final FilterConfig filterConfig)
        throws ServletException {
    }

    @Override
    public void doFilter(
        final ServletRequest request, final ServletResponse response,
        final FilterChain chain)
        throws IOException, ServletException {
    }

    @Override
    public void destroy() {
    }
}

It’s not a big deal if you presume that those are actually instances of HTTP version.

@Override
public void doFilter(final ServletRequest request,
                     final ServletResponse response,
                     final FilterChain chain)
    throws IOException, ServletException {

    final HttpServletRequest hequest = (HttpServletRequest) request;
    final HttpServletResponse hesponse = (HttpServletResponse) response;

    // happy, now?
}

I quickly tired of doing this.

public abstract class HttpFilter implements Filter {

    @Override
    public void doFilter(final ServletRequest request,
                         final ServletResponse response,
                         final FilterChain chain)
        throws IOException, ServletException {

        if (request instanceof HttpServletRequest
            && response instanceof HttpServletResponse) {

            doFilter((HttpServletRequest) request,
                     (HttpServletResponse) resposne, chain);

           return;
        }

        chain.doFilter(request, response, chain);
    }

    protected abstract void doFilter(HttpServletRequest request,
                                     HttpServletResponse response,
                                     FilterChain chain)
        throws IOException, ServletException;
}

Now I can do this.

public class MyFilter extends HttpFilter {

    @Override
    protected void doFilter(final HttpServletRequest request,
                            final HttpServletResponse response,
                            final FilterChain chain)
        throws IOException, ServletException {

        // never bean happier. :)
    }
}

Full source is here.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s