Servlet 环境设置
JDK、Tomcat、目录结构与 IDEA 工程骨架。
Key PointsWeb 应用的根目录里,WEB-INF 是唯一不能被浏览器直接访问的目录——classes、lib、web.xml 都放在里面。
需要什么
| Component | Purpose |
|---|---|
| JDK | 编译 Servlet,运行容器 |
| Servlet 容器 | Tomcat / Jetty,提供 jakarta.servlet 实现 |
| Build tool | Maven / Gradle,管理依赖与打 war 包 |
| IDE | IntelliJ 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/ # 依赖 jarThe 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/helloOutput
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.需要什么
| 组件 | 用途 |
|---|---|
| JDK | 编译 Servlet,运行容器 |
| Servlet 容器 | Tomcat / Jetty,提供 jakarta.servlet 实现 |
| 构建工具 | Maven / Gradle,管理依赖与打 war 包 |
| IDE | IntelliJ 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浏览器能访问 webapp/ 下的一切,唯独进不去 WEB-INF/。所以把 web.xml、编译后的 class、第三方 jar 放进去,就天然挡住了外部直接下载。
Maven 依赖
XML
<dependencies>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>6.0.0</version>
<scope>provided</scope>
</dependency>
</dependencies>provided 的意思是:编译时需要,打包时不要。因为容器自己带着这套 API,打进 war 里反而会和容器的版本打架。
验证环境
启动容器后访问首页,返回 200 就说明环境通了。Tomcat 默认端口 8080,应用部署为 myapp.war 后访问路径是 /myapp/。
Bash
curl -i http://localhost:8080/myapp/helloOutput
HTTP/1.1 200 OK
Content-Type: text/html;charset=UTF-8
Content-Length: 26
<h1>Hello, Servlet</h1>端口被占用时改
conf/server.xml 里的 Connector port。部署失败先看 logs/catalina.out,SEVERE 行通常就是根因,最常见的是包名 javax 与容器 jakarta 不匹配。