1

I am studying Java Web. I added the dependency and created a servlet class. After starting tomcat, I received the errors that this is not a servlet and cannot be cast to jakarta.servlet.Servlet. Could you help me find what the root cause is?

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("hello servlet");
        PrintWriter writer = resp.getWriter();
        writer.print("hello,servlet");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
Wendy Yu
  • 11
  • 2
  • 1
    Does this answer your question? [Servlet 5.0 JAR throws compile error on javax.servlet.\* but Servlet 4.0 JAR does not](https://stackoverflow.com/questions/64387472/servlet-5-0-jar-throws-compile-error-on-javax-servlet-but-servlet-4-0-jar-does) – Piotr P. Karwasz Mar 01 '21 at 07:26
  • 2
    Replace `javax` with `jakarta` since you are probably using Tomcat 10. – Piotr P. Karwasz Mar 01 '21 at 07:27
  • 1
    I am guessing that you are using the wrong version of Tomcat. Oracle handed custody of Servlet technology to the Eclipse Foundation, changing the package namespace from `javax.Servlet` to `jakarta.Servlet`. Tomcat 10 is built for the new namespace, and Tomcat 9 is for the old namespace. – Basil Bourque Mar 01 '21 at 07:27
  • Yes, I followed up on your suggestions. Replace the javax with jakarta imported in the code and the problem is fixed. Thanks for your help. – Wendy Yu Mar 02 '21 at 02:51

0 Answers0