如何解决 java.lang.NoSuchMethodException: package.MyCustomFilter.<init>() while starting the servlet filter

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

应用程序服务器无法启动 servlet 筛选器。 错误消息是 java.lang.NoSuchMethodException: package.MyCustomFilter.<init>()。 HttpFilter 扩展了实现 init() 方法的 GenericFilter。所以没有必要覆盖它。我已经尝试覆盖 init() 方法,但它没有解决问题。

过滤器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>

我发现 <init>() 不是 Filter 中的 init() 方法。异常告诉我们没有 public 构造函数。每个 Servlet 过滤器都需要一个 public 构造函数。只需添加一个,问题就解决了。在我的示例中,您还可以删除不必要的受保护构造函数。否则,将使用默认构造函数。