Servlet 环境设置

JDK、Tomcat、目录结构与 IDEA 工程骨架。

Beginner
Key PointsWeb 应用的根目录里,WEB-INF 是唯一不能被浏览器直接访问的目录——classes、lib、web.xml 都放在里面。

需要什么

ComponentPurpose
JDK编译 Servlet,运行容器
Servlet 容器Tomcat / Jetty,提供 jakarta.servlet 实现
Build toolMaven / Gradle,管理依赖与打 war 包
IDEIntelliJ IDEA / Eclipse,调试与热部署

标准目录结构

Text
myapp/
├── pom.xml
└── src/main/
    ├── java/
    │   └── com/example/HelloServlet.java
    └── webapp/
        ├── index.jsp
        ├── css/style.css
        └── WEB-INF/
            ├── web.xml
            ├── classes/          # 编译产物(war 里由 Maven 填充)
            └── lib/              # 依赖 jar

The browser can reach everything under webapp/ except WEB-INF/. That is why web.xml, compiled classes and third-party jars live inside it — they are shielded from direct download.

Maven 依赖

XML
<dependencies>
  <dependency>
    <groupId>jakarta.servlet</groupId>
    <artifactId>jakarta.servlet-api</artifactId>
    <version>6.0.0</version>
    <scope>provided</scope>
  </dependency>
</dependencies>

provided means: needed to compile, excluded from the package. The container already ships this API, and bundling it would clash with the container's own version.

验证环境

Start the container and request the home page; a 200 means the environment works. Tomcat listens on 8080 by default, and a myapp.war is served under /myapp/.

Bash
curl -i http://localhost:8080/myapp/hello
Output
HTTP/1.1 200 OK
Content-Type: text/html;charset=UTF-8
Content-Length: 26

<h1>Hello, Servlet</h1>
If the port is taken, change Connector port in conf/server.xml. When a deployment fails, read logs/catalina.out — the SEVERE line is usually the root cause, most often a javax vs jakarta package mismatch.

Friends & Partners