默认情况下Spring Boot使用了内嵌的Tomcat服务器,项目最终被打成jar包运行,每个jar包可以被看作一个独立的Web服务器。
传统的Web开发,一般会将Web应用打成一个war包,然后将其部署到Web服务器中运行。
Spring Boot也支持传统的部署模式。
开发环境:IntelliJ IDEA 2019.2.2
Spring Boot版本:2.1.8
1、新建一个名称为demo的Spring Boot项目。
2、修改pom.xml文件
下面粗体部分为所加代码,注释掉原来的build节点,该项目最终会打包成一个war-demo的war包。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<packaging>war</packaging>
<build>
<finalName>war-demo</finalName>
</build> <properties>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> </dependencies> <!-- <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>--> </project>
3、修改启动类方法 DemoApplication.java
继承SpringBootServletInitializer,重写父类configure方法。增加测试用的控制器。
package com.example.demo; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; @SpringBootApplication
@RestController
public class DemoApplication extends SpringBootServletInitializer { protected SpringApplicationBuilder configure(SpringApplicationBuilder application){
return application.sources(DemoApplication.class);
} public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
} @RequestMapping("/")
public String test(){
return "test";
}
}
4、先后点击IDEA的Maven窗口的clean和package
到项目的target目录下,可看到生成了一个war-demo.war,把它拷贝到Tomcat的webapps目录下,启动Tomcat,
访问http://localhost:8080/war-demo/,可看到页面输出:test
附,项目结构: