Search code examples
javatomcatservlet-filtersapache-tomee

How to solve java.lang.NoSuchMethodException: package.MyCustomFilter.<init>() while starting the servlet filter


The application server cannot start the servlet filter. The error message is java.lang.NoSuchMethodException: package.MyCustomFilter.<init>(). HttpFilter extends GenericFilter which implements the init() method. So there is no need to override it. I already tried to override the init() method it did not solve the problem.

Filter class:

public class MyCustomFilter extends HttpFilter {

    private static final long serialVersionUID = -5281928035553598730L;
    private static Logger log = Logger.getLogger(MyCustomFilter.class.getName());

    protected MyCustomFilter() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        super.doFilter(req, res, chain);
        log.info("filter Request");
    }

}

web.xml


<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0">
       ...
     <filter>
        <filter-name>myCustomFilter</filter-name>
        <filter-class>com.dtmarius.gateway.filter.MyCustomFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>myCustomFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

Solution

  • I found out that <init>() is not the init() method from the Filter. The Exception is telling us there is no public constructor. Every Servlet filter needs an public constructor. Just add one and the problem is solved. In my example you could also remove the unnecessary protected constructor. Without that the default constructor is used.