最近在做一个项目,遇到了项目打成 war 包的一个问题,项目创建时选择的时 jar 包方式,后因项目部署要求,需要打成 war 包部署,遇到很多坑,在此做一下记录
一、修改打包方式
原:
0.0.1-SNAPSHOT
jar
改后:
0.0.1-SNAPSHOT
war
二、排除内置 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.34
provided
四、改变项目的构造方式
原:
org.springframework.boot
spring-boot-maven-plugin
改后:
demo
org.apache.maven.plugins
maven-compiler-plugin
${java.version}
${java.version}
org.apache.maven.plugins
maven-war-plugin
src/main/resources/lib
WEB-INF/lib/
**/*.jar
五、修改启动类
启动类继承 SpringBootServletInitializer,并实现 configure() 方法
原:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public 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
@EnableScheduling
public 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="@{}" rel="external nofollow" 的方式,去引入静态资源文件
八、测试
我们可以不使用项目的启动类启动项目,我们自己添加一个服务器来启动项目
就想普通的 SSM 项目,添加一个 Tomcat 启动项目,如果能够成功启动项目,并能正常访问,那么打成 war 包也能够正常运行
到此这篇关于SpringBoot中打war包需要注意事项的文章就介绍到这了,更多相关SpringBoot打war包内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!