一、设置打包方式

在pom.xml中设置打包格式

<packaging>war</packaging>

二、取消Spring Boot的tomcat

<!--部署成war包时开启↓↓↓↓-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
    <scope>provided</scope>
</dependency>
<!--部署成war包时开启↑↑↑↑-->

scope的provided参数可以参考我另一篇博客provided参数

取消默认的tomcat之后,还需要再排除spring-boot-starter-web中的一些web包

否则会启动失败

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
         <exclusion>
             <groupId>javax.servlet</groupId>
             <artifactId>javax.servlet-api</artifactId>
         </exclusion>
    </exclusions>
 </dependency>

三、重写启动类SpringBootApplication.java

继承 SpringBootServletInitializer重写 configure方法

@SpringBootApplication
public class SpringBootApplication extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(SpringBootApplication.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(SpringBootApplication.class, args);
    }
}

四、修改打包的名称(可选)

application.yml的

server:
    servlet:
        context-path: /springboot

和pom.xml

<build>
    <finalName>springboot</finalName>
</build>

必须保持一致

12-28 07:58