HttpServlet定义归属疑问:Java EE还是Web容器?兼问Java EE与Servlet规范及实现关系
Great question! This is a super common point of confusion when diving into Servlet development, so let's break it down clearly:
1. Servlet 是 Java EE(现 Jakarta EE)定义的规范
First off, Servlet is a specification—it's a set of rules and APIs that define how Java code interacts with a web server to handle HTTP requests. Java EE (now rebranded as Jakarta EE) is the body that creates this specification, which includes:
- The core packages:
javax.servlet(for base Servlet interfaces) andjavax.servlet.http(for HTTP-specific extensions) - Key abstract classes/interfaces: Like the
Servletinterface,GenericServletabstract class, and yes, theHttpServletabstract class
These specification-defined classes are provided by Java EE/Jakarta EE itself—you'll find them in dependencies like javax.servlet-api (for Java EE) or jakarta.servlet-api (for Jakarta EE). But here's the key: these are just the abstract layer of the spec. HttpServlet implements the Servlet interface and handles generic HTTP request logic (like routing GET/POST to doGet()/doPost()), but it doesn't contain the full runtime code needed to make everything work.
2. Web容器提供规范的实际运行实现
Tools like Tomcat, Jetty, or WildFly are called web containers, and they're the ones that build out the full, runnable implementation of the Servlet spec. Their job includes:
- Writing concrete code for the
Servletinterface's lifecycle methods (init(),service(),destroy()) - Parsing incoming HTTP requests, routing them to the right Servlet, and generating responses
- Managing Servlet instances, thread pools, and session handling
- Implementing all the other behind-the-scenes services the spec requires
For example: When you write a custom Servlet that extends HttpServlet, you only need to override doGet() or doPost(). The logic that checks the request method and calls your overridden method comes from HttpServlet, but the code that actually starts the server, listens for requests, and executes your Servlet is all part of the web container's implementation.
3. 解答你的核心困惑
To directly address your question: Does Java EE both define the Servlet spec and provide its implementation? The answer is 部分是,部分不是:
- Java EE 绝对定义了完整的Servlet规范,并且提供了规范中的核心抽象类(比如
HttpServlet)——这些类是规范的一部分,目的是简化开发者的编码工作。 - 但让Servlet系统真正运转起来的完整可运行实现,是由Web容器厂商提供的,而非Java EE本身。
这样拆分下来,应该就能理清规范与实际实现的边界啦!
内容的提问来源于stack exchange,提问作者sql_dummy

