Maven Web 应用
完整演练使用 maven-archetype-webapp 生成 trucks Java Web 工程、核对标准 webapp/WEB-INF 目录布局与 war 打包 POM、执行 mvn clean package 产出 trucks.war,以及将其部署至 Servlet 容器验证访问。
学完这一章,你能够
- 完整演练使用 maven-archetype-webapp 生成 trucks Java Web 工程、核对标准 webapp/WEB-INF 目录布局与 war 打包 POM、执行 mvn clean package 产出 trucks.war,以及将其部署至 Servlet 容器验证访问。
使用 maven-archetype-webapp 创建 Web 项目
除普通 JAR 库外,Maven 同样原生支持 Java Web 项目的全生命周期管理(注意 Maven 是项目管理与构建工具,而非 Git/SVN 这类版本控制系统)。在工作目录(如 `C:\MVN`)执行 `mvn archetype:generate -DgroupId=com.companyname.automobile -DartifactId=trucks -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false`,即可快速生成符合 Servlet 规范的 `trucks` Web 项目骨架,包含 `src/main/webapp`、`WEB-INF/web.xml` 及资源目录(各目录职责见下方参考表)。
查看生成的 `trucks/pom.xml` 可以注意到两个与 JAR 项目的关键差异:`<packaging>` 为 `war`,且 `<build><finalName>trucks</finalName></build>` 将输出包名固定为不含版本号后缀的 `trucks.war`(便于部署后直接映射到 `/trucks` 上下文路径);依赖区默认包含 `test` 作用域的 JUnit。在 `src/main/webapp/` 下模板已预置了输出 `<h2>Hello World!</h2>` 的初始 `index.jsp` 页面。
打包 WAR、部署容器与浏览器访问验证
进入 `trucks` 目录运行 `mvn clean package`,`maven-war-plugin:war` 会将 `src/main/webapp` 下的 JSP、静态资源、`WEB-INF/web.xml`、编译后的类文件(`WEB-INF/classes`)及 `compile`/`runtime` 依赖 JAR(`WEB-INF/lib`,自动排除 `test` 作用域的 JUnit)统一封装为 `target/trucks.war`。随后把 `trucks.war` 复制到 Tomcat/Jetty 等 Servlet 容器的 `webapps/` 目录并启动服务,在浏览器访问 `http://<主机>:<端口>/trucks/index.jsp`(例如本机默认 `http://localhost:8080/trucks/index.jsp`;源文档中 `http://:/trucks/index.jsp` 为省略主机与端口的占位写法)即可看到渲染出的 `Hello World!` 页面。本站离线脚本已使用 `zipfile` 实测封装 `trucks.war` 并校验了 `WEB-INF/` 结构与测试依赖排除。
trucks Java Web 项目标准目录结构
| 目录路径 | 用途描述 |
| trucks | Web 项目根目录,包含 `src/` 目录与 `pom.xml` 构建描述文件。 |
| src/main/webapp | Web 应用文档根目录,存放 `index.jsp`、静态资源与 `WEB-INF` 目录。 |
| src/main/webapp/WEB-INF | 受容器保护的私有配置目录,存放部署描述符 `web.xml`。 |
| src/main/resources | 存放类路径下的图片、`.properties` 与框架配置文件。 |
运行 Maven Webapp POM、真实 zipfile WAR 归档组装(WEB-INF/ 与 test 排除)及部署 URL 离线核验
展开查看收起
"""Offline Maven webapp archetype, WAR packaging (WEB-INF/) & deployment verifier for Ch22 (web-application)."""
import json
import tempfile
import xml.etree.ElementTree as ET
import zipfile
from pathlib import Path
VERSION = "CPython 3.12.14 offline Maven POM/lifecycle/dependency verifier (mvn CLI absent)"
def check(name, summary, expected, actual):
return {
"name": name,
"summary": summary,
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = []
# Case 1: Parse maven-archetype-webapp POM (packaging=war, finalName=trucks)
pom_xml = """
<project xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>com.companyname.automobile</groupId>
<artifactId>trucks</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>trucks Maven Webapp</name>
<dependencies>
<dependency>
<groupId>junit</groupId><artifactId>junit</artifactId><version>3.8.1</version><scope>test</scope>
</dependency>
</dependencies>
<build><finalName>trucks</finalName></build>
</project>
"""
ns = {"m": "http://maven.apache.org/POM/4.0.0"}
root = ET.fromstring(pom_xml)
cases.append(
check(
"webapp_archetype_and_pom_parse",
"Parse trucks webapp pom.xml verifying packaging=war, build/finalName=trucks, and junit test scope",
{
"gav": "com.companyname.automobile:trucks:1.0-SNAPSHOT",
"packaging": "war",
"finalName": "trucks",
"war_filename": "trucks.war",
},
{
"gav": f"{root.findtext('m:groupId', namespaces=ns)}:{root.findtext('m:artifactId', namespaces=ns)}:{root.findtext('m:version', namespaces=ns)}",
"packaging": root.findtext("m:packaging", namespaces=ns),
"finalName": root.findtext("m:build/m:finalName", namespaces=ns),
"war_filename": f"{root.findtext('m:build/m:finalName', namespaces=ns)}.{root.findtext('m:packaging', namespaces=ns)}",
},
)
)
# Case 2: Standard Web directory layout & index.jsp content check
index_jsp = "<html>\n <body>\n <h2>Hello World!</h2>\n </body>\n</html>\n"
web_xml = "<web-app><display-name>Archetype Created Web Application</display-name></web-app>"
with tempfile.TemporaryDirectory() as tmp:
proj = Path(tmp) / "trucks"
webinf = proj / "src/main/webapp/WEB-INF"
res_dir = proj / "src/main/resources"
webinf.mkdir(parents=True)
res_dir.mkdir(parents=True)
(proj / "pom.xml").write_text(pom_xml, encoding="utf-8")
(proj / "src/main/webapp/index.jsp").write_text(index_jsp, encoding="utf-8")
(webinf / "web.xml").write_text(web_xml, encoding="utf-8")
layout_ok = all(
p.exists()
for p in [
proj / "pom.xml",
proj / "src/main/webapp/index.jsp",
webinf / "web.xml",
res_dir,
]
)
# Case 3: Assemble real target/trucks.war via zipfile and verify WEB-INF/ structure & test-scope exclusion
war_path = proj / "target/trucks.war"
war_path.parent.mkdir(parents=True)
with zipfile.ZipFile(war_path, "w") as zf:
zf.writestr("META-INF/MANIFEST.MF", "Manifest-Version: 1.0\n")
zf.write(proj / "src/main/webapp/index.jsp", "index.jsp")
zf.write(webinf / "web.xml", "WEB-INF/web.xml")
zf.writestr("WEB-INF/classes/.keep", "")
# Only compile/runtime dependencies enter WEB-INF/lib; junit (test) must be excluded
deps = [("junit-3.8.1.jar", "test")]
for jar_name, scope in deps:
if scope in ("compile", "runtime"):
zf.writestr(f"WEB-INF/lib/{jar_name}", b"")
with zipfile.ZipFile(war_path, "r") as zf:
war_entries = sorted(zf.namelist())
junit_excluded = not any("junit" in e for e in war_entries)
cases.append(
check(
"webapp_directory_layout_and_jsp",
"Verify trucks webapp 4-directory standard layout and index.jsp Hello World heading",
{"layout_ok": True, "has_hello_h2": True},
{"layout_ok": layout_ok, "has_hello_h2": "<h2>Hello World!</h2>" in index_jsp},
)
)
cases.append(
check(
"war_archive_assembly_and_verification",
"Build target/trucks.war via zipfile verifying index.jsp, WEB-INF/web.xml, WEB-INF/classes, and test-scope junit exclusion",
{
"entries": ["META-INF/MANIFEST.MF", "WEB-INF/classes/.keep", "WEB-INF/web.xml", "index.jsp"],
"junit_excluded_from_war": True,
},
{"entries": war_entries, "junit_excluded_from_war": junit_excluded},
)
)
# Case 4: Servlet container WAR deployment context path & complete URL check
final_name = "trucks"
host, port = "localhost", 8080
full_url = f"http://{host}:{port}/{final_name}/index.jsp"
cases.append(
check(
"war_deployment_url_and_context_path",
"Verify WAR deployment context path (/trucks) and valid http://localhost:8080/trucks/index.jsp URL format",
{"context_path": "/trucks", "example_url": "http://localhost:8080/trucks/index.jsp"},
{"context_path": f"/{final_name}", "example_url": full_url},
)
)
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
`<finalName>trucks</finalName>` 使打包产物固定命名为 `trucks.war`(去掉 `-1.0-SNAPSHOT` 后缀),部署到 Tomcat 等容器后上下文路径即简洁的 `/trucks`;`maven-war-plugin` 仅将 `compile`/`runtime` 依赖打入 `WEB-INF/lib/`,不会打包 `test` 作用域的 JUnit。