最近在做一个项目,遇到了项目打成 war 包的一个问题,项目创建时选择的时 jar 包方式,后因项目部署要求,需要打成 war 包部署,遇到很多坑,在此做一下记录
一、修改打包方式
原:
0.0.1-SNAPSHOTjar
改后:
0.0.1-SNAPSHOTwar
二、排除内置 Tomcat
原:
org.springframework.boot spring-boot-starter-web
改后:
org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-tomcat
使用 排除内置服务器
三、添加 Tomcat 依赖
用于编译和测试开发,两种方式
1、
org.springframework.boot spring-boot-starter-tomcat provided
2、
org.apache.tomcat tomcat-servlet-api 8.5.34provided
四、改变项目的构造方式
原:
org.springframework.boot spring-boot-maven-plugin
改后:
demoorg.apache.maven.plugins maven-compiler-plugin ${java.version}${java.version}org.apache.maven.plugins maven-war-plugin src/main/resources/libWEB-INF/lib/**/*.jar
五、修改启动类
启动类继承 SpringBootServletInitializer,并实现 configure() 方法
原:
import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); }}
改后:
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.scheduling.annotation.EnableScheduling;@SpringBootApplication@EnableSchedulingpublic class DemoApplication extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(DemoApplication.class); } public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); }}
六、修改配置文件
修改 application.yml 文件,标明项目项目上下文路径 context-path
server: servlet: context-path: /demo
七、修改静态资源引入方式
我们使用 thymeleaf 模板引擎,引入 css、js 文件时,需要加上项目上下文路径
原:
改后:
我们需要使用 th:href="@{}" 的方式,去引入静态资源文件
八、测试
我们可以不使用项目的启动类启动项目,我们自己添加一个服务器来启动项目
![a34a07cec8259f4381ff264095178b7d.png](https://i-blog.csdnimg.cn/blog_migrate/c151447d9ee4446255b11c4b6ac59a85.jpeg)
就想普通的 SSM 项目,添加一个 Tomcat 启动项目,如果能够成功启动项目,并能正常访问,那么打成 war 包也能够正常运行
以上就是我在使用 SpringBoot 打成 war 包遇到的问题,希望能够帮助你
如您在阅读中发现不足,欢迎留言!!!