Servlet 5.0 JAR throws compile error on javax.servlet.* but Servlet 4.0 JAR does not

When I place the .class file in the corresponding Tomcat directory, start the server and try to interact with the app, I get the following exception:

java.lang.ClassNotFoundException: javax.servlet.http.HttpServlet

I tried placing the javax.servlet-api-4.0.1 in the Tomcat/lib directory, but then I get:

java.lang.ClassCastException: class com.example.controllers.BeerSelect
                       cannot be cast to class jakarta.servlet.Servlet

The jakarta.servlet.Servlet is part of Servlet API version 5.0 which in turn is part of Jakarta EE version 9. Your servlet is actually extending from javax.servlet.Servlet which in turn is part of an older JEE version which is actually not supported by your target runtime (Tomcat 10.x).

You have 2 options:

  1. Replace the javax.servlet.* imports in your code by jakarta.servlet.* ones.

    import jakarta.servlet.*;
    import jakarta.servlet.http.*;
    

    Then you can just compile against the libraries from a Servlet 5.0 based target runtime.

  2. Or, downgrade the servlet container from Servlet API version 5.0 to a previous version, at least the one still having the javax.servlet.* package name. Tomcat 9.x is the latest one still having the old package.

The technical reason is that during the step from Java/Jakarta EE 8 to Jakarta EE 9 all javax.* packages have been renamed to jakarta.* packages. So there is no backwards compatibility anymore since Jakarta EE 9.

So, when following any servlet tutorials which still use the old javax.servlet.* package while you’re using Tomcat 10 or newer, then you need to manually swap out the package used in code examples for the jakarta.servlet.* one. Generally it’ll work just fine.

See also:

Leave a Comment