蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 Maven Webapp POM、真实 zipfile WAR 归档组装(WEB-INF/ 与 test 排除)及部署 URL 离线核验

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-web-application.py
explore-web-application.py139 行
"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/maven-web-application-lab/explore-web-application.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-web-application.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Maven

课程关联工程包(登记关联25章) · 含当前章节或实例 · mbskycom202612a2175.zip

下载课程关联工程包:Maven

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2200.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习