Skip to content

War 插件

war 插件用于构建 Web 应用 WAR 文件,适用于部署到 Tomcat、Jetty 等 Servlet 容器。

基本配置

kotlin
plugins {
    war
}

dependencies {
    // Servlet API(compile only,由容器提供)
    compileOnly("jakarta.servlet:jakarta.servlet-api:6.0.0")
    
    // 应用依赖(打包进 WAR)
    implementation("org.springframework:spring-webmvc:6.1.1")
    implementation("com.fasterxml.jackson.core:jackson-databind:2.15.3")
}

tasks.named<War>("war") {
    archiveFileName.set("my-web-app.war")
    
    // 自定义 WEB-INF 内容
    webInf {
        from("src/main/webapp/WEB-INF")
    }
    
    // 额外文件
    from("src/main/resources") {
        into("WEB-INF/classes")
    }
}

WAR 目录结构

my-web-app.war
├── index.html              ← src/main/webapp/ 中的静态文件
├── WEB-INF/
│   ├── web.xml             ← Web 描述符
│   ├── classes/            ← 编译后的类和资源
│   │   ├── com/example/
│   │   └── applicationContext.xml
│   └── lib/                ← 依赖 JAR(不含 compileOnly)
│       ├── spring-webmvc.jar
│       └── jackson-databind.jar
└── META-INF/

Spring Boot WAR 部署

kotlin
plugins {
    war
    id("org.springframework.boot") version "3.2.0"
}

// Spring Boot 项目需要继承 SpringBootServletInitializer
// 同时配置可执行 WAR
tasks.named<BootWar>("bootWar") {
    archiveFileName.set("app.war")
}

// 使普通 war 任务也可用(如需部署到外部容器)
tasks.named<War>("war") {
    enabled = true
}

下一步