原因分析:
- 未去除springboot内置tomcat配置
- 访问路径为加上war包名字(tomcat下访问与idea启动访问略有不同)
去除springboot内置tomcat配置
- 修改pom.xml文件
注:packaging 属性必须为war
添加去除内嵌tomcat配置
代码如下:
<!--忽略内嵌tomcat,打包部署到tomcat。注*本地运行的时候要把这一段忽略引入个注释掉,要不然项目启动不了-->
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
- 在启动类同级添加继承SpringBootServletInitializer 的类
代码如下:
package com.example;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
/**
1. <p>解决springboot打成war包,部署tomcat后访问404问题</p>
*/
public class BackendInTomcatApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
}
3.用idea打包
先clean下,清理下无效文件;然后点击package打包
打包成功包位置:
至此,war包已经完成
启动tomcat,访问项目
1.将以上所打war包放置在指定tomcat版本的webapps目录下
这里涉及到一个tomcat版本建议和springboot内置tomcat版本一致,否则可能会有兼容性问题
查看springboot内置tomcat版本:
比如我们需要查Spring Boot 2.0.6.RELEASE的内嵌Tomcat版本, 可以打开链接:
https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-tomcat/2.0.6.RELEASE
所以我这里用的是tomcat8.5版本
启动tomcat:
可以看到我的web层测试方法已经起效:
2.访问