如何修复ClassNotFoundException:javax.servlet.http.HttpFilter

时间:2019-08-04 13:32:59

标签: java maven jsp tomcat servlets

启动应用程序后,我收到ClassNotFoundException:javax.servlet.http.HttpFilter。

过滤器必须将未登录的用户重定向到登录页面

Pom.xml

<dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.3</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.9</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

AuthenticationFilter.java

@WebFilter("/to-do/*")
public class AuthenticationFilter extends HttpFilter {
    @Override
    public void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
        if (AuthenticationService.isAuthenticated(req)){
            super.doFilter(req,res,chain);
        }else{
            res.sendRedirect("/");
        }
    }
}

Tomcat日志:

java.lang.NoClassDefFoundError: javax/servlet/http/HttpFilter
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
[...]
Caused by: java.lang.ClassNotFoundException: javax.servlet.http.HttpFilter
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1344)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1172)
    ... 59 more

当我评论@WebFilter应用程序时,效果很好。我试图在web.xml中添加fiter,但它也无法正常工作; /

1 个答案:

答案 0 :(得分:1)

您至少需要使用Tomcat版本 9 -*当Tomcat 8 is implementing Servlet 3.1 Servlet 4.0 中引入了HttpFilter ** >

另一种方法是在版本 8

中添加依赖项javaee-api
<dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-api</artifactId>
    <version>8.0</version>
</dependency>