Spring Boot 打成 WAR 包通常需要以下步骤:
- 在
pom.xml中修改打包方式为war:
<packaging>war</packaging>- 添加
spring-boot-starter-web依赖,并排除嵌入式容器(Tomcat、Jetty 等):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>- 添加
provided作用域的servlet-api和jsp-api依赖:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>- 创建
SpringBootServletInitializer的子类并覆盖configure方法:
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(YourApplication.class);
}
}- 打包时使用
mvn clean package。
Vue 打成 WAR 包并部署到 Tomcat 或 WebSphere 中,你需要做以下操作:
- 在 Vue 项目中执行
npm run build来生成dist/文件夹。 - 将生成的
dist/文件夹复制到 Spring Boot 项目的src/main/webapp目录(如果不存在则创建)。 - 在
src/main/webapp下创建index.html文件,确保有正确的publicPath和assetsDir。 - 修改
application.properties或application.yml文件,确保静态资源的映射正确:
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/- 打包 Spring Boot 项目,上述步骤已经包含了如何打包成 WAR。
- 将生成的 WAR 包部署到 Tomcat 或 WebSphere。
在部署时,确保 Tomcat 或 WebSphere 的 Servlet 容器没有覆盖你的 Spring Boot 应用。通常,Spring Boot 的应用会在 web.xml 中配置或者通过注解的方式启动。如果你使用的是 Spring Boot 2.x 版本,默认使用内嵌的 Tomcat,你需要将其关闭并配置外部的 Servlet