Experts,
The servlet API has a class HttpServlet which extends GenericServlet which
implements Servlet.
For filters, there's only Filter. Implementing this interface directly
incurs the following:
1) There are three methods to implement (init, destroy, doFilter). Most
often I only care about doFilter, so the other two are left empty.
2) doFilter takes ServletRequest and ServletResponse. In 95% of my cases I
need to cast these to HttpServletRequest and HttpServletResponse before I
can do anything useful.
3) If I need access to FilterConfig I need to assign it to a field in init(
FilterConfig)
Compare this to HttpFilter:
1) If I only care about doGet, that's the only method I need to override.
2) All do*-methods take HttpServletRequest, HttpServletResponse parameters,
so I don't need to cast.
3) GenericServlet already has the convenience methods getInitParameter*,
getServletConfig, getServletContext, getServletName and log.
Considering this usability asymmetry between servlets and filters, I
propose we add two new classes to the Servlet API, mostly adopted from it's
servlet cousins:
(Method bodies removed for readability)
public abstract class GenericFilter implements Filter {
@Override
public void destroy() { .. }
public String getInitParameter(String name) { .. }
public Enumeration<String> getInitParameterNames() { .. }
public FilterConfig getFilterConfig() { .. }
public ServletContext getServletContext() { .. }
public void init(FilterConfig config) throws ServletException { .. }
public void init() throws ServletException { .. }
public void log(String msg) { .. }
public String getFilterName(){ .. }
}
and:
public abstract class HttpFilter extends GenericFilter {
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {}
protected abstract void doFilter(HttpServletRequest request,
HttpServletResponse response, FilterChain chain) throws IOException,
ServletException ;
}
Adding these two classes will improve the usability of filters, reduce the
amount of boiler plate code, and make filter code more readable.
The cost is adding two new classes. But these classes are symmetric to the
already present HttpServlet / GenericServlet, so the conceptual surface
increase is minimal.
What do the exports think about this? Is this something we could consider
adding in the Servlet 4 time frame?
Thanks,
Eirik Bjørsnøs