关于springboot分布式项目部署到本地tomcat成功后 访问404错误

问题概述
分布式项目写完后,发现打包以及部署遇到了很多坑,百度的解决方案也没有一个特别完善的,特在此整理出解决的方案
主要问题:在ide上运行成功的springboot分布式项目,打包后部署至tomcat中,无法正常访问
可能报错类型

  1. No goals have been specified for this build. You must specify a valid lifecycle phase or a goal in the format : or :[:]:. Available lifecycle phases are: validate, initialize, generate-sources, process-sources, generate-resources, process-resources, compile, process-classes, generate-test-sources, process-test-sources, generate-test-resources, process-test-resources, test-compile, process-test-classes, test, prepare-package, package, pre-integration-test, integration-test, post-integration-test, verify, install, deploy, pre-clean, clean, post-clean, pre-site, site, post-site, site-deploy. -> [Help 1]
    这个错误看第一句就好了,需要在pom文件里的的build标签中添加 <defaultGoal>compile</defaultGoal>标签就OK了

  2. 打包并部署到tomcat成功,但是使用localhost:xxxx端口号却报404错误或white页错误,
    极有可能是因为jar包冲突引起的,具体解决方案看下面的操作步骤xxx

分布式项目打包部署流程
这里是打war包的教程

  1. 修改依赖默认配置
    由于springboot分布式项目是内置的tomcat,所以在打包时,我们需要在parent中设置依赖,将与内置tomcat有关的jar包设为只在编译和测试时使用,他们打包时就不会加入项目中了。否则war包在tomcat中运行时会报jar包冲突的错误。
    关键代码<scope>provided</scope>这个字段能让dependency只在编译和测试时使用
    具体操作:在parent中的pom文件的dependencies标签对中添加如下4个依赖
<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>
<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>jsp-api</artifactId>
     <version>2.1</version>
     <scope>provided</scope>
</dependency>
<dependency>
     <groupId>javax.servlet</groupId>
     <artifactId>javax.servlet-api</artifactId>
     <version>3.1.0</version>
     <scope>provided</scope>
</dependency>
  1. 启动类继承SpringBootServletInitializer并重写configure方法
    由于我们在平时写spring分布式项目时是没有配置web.xml的,这里重写这个方法的作用就是起到一个类似于加载web.xml的作用
@SpringBootApplication
public class StarterWeb extends SpringBootServletInitializer{
	public static void main(String[] args) {
		SpringApplication.run(StarterWeb.class, args);
	}
	
	@Override
	protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
		// TODO Auto-generated method stub
		return builder.sources(StarterWeb.class);
		//return null;
	}
}
  1. 建立修改web.xml
    如果项目的WEB-INF下没有web.xml,可能也会导致运行报错,因为war包最后是在tomcat中运行的,他需要一个web.xml的默认文件,这里如果是前台web应用,最好将欢迎页设置为首页
<web-app>
  <welcome-file>/</welcome-file>
</web-app>
  1. 部署到tomcat
    右键项目->run as -> maven clean 清除掉之前打包的文件
    右键项目->run as -> maven install 开始打包
    打包完成后,在项目的target目录下会出现名XXXX.war的文件(XXXX是应用名)
    然后将war包丢进tomcat的webapps目录下,启动tomcat/bin/startup.bat即可
    如果应用有静态资源,此时访问时localhost:8080/XXXX,就能访问到默认的首页了
    想设置为默认应用就将war包改名为ROOT.war即可
    部署时tomcat的版本尽量高一点,避免因为tomcat版本出现问题;

    如果写的有什么问题,欢迎指出

猜你喜欢

转载自blog.csdn.net/weixin_43495429/article/details/88997999