Springboot在idea中直接运行没有问题,打war包,部署到外置的Tomcat容器后,却无法访问项目

前言

最近,在搞Springboot,新建了一个项目,发现在Intellij Idea中可以通过内置的容器运行,可以正常访问,但是,打成war包后,手动部署到Tomcat后,服务可以正常起来,但是,无法访问资源,总是爆404的错误

原因

最开始,我开始猜想是路径配置有误或者访问的路径有误,顺着这个线索找了下,发现不对;又去看了tomcat的启动日志,和访问日志,均没有任何异常(少了Springboot的logo),而且在tomcat中的manager管理页面中,新建的war项目是确确实实运行了起来的,而且也没有任何异常;如下图

我就开始对比之前建的的项目,发现少了一个继承SpringBootServletInitializer的类,就试着把这个类添加进去,果不其然,运行起来后,就可以访问了

package demo.demo;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;


public class ServletInitializer extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(DemoApplication.class);
    }
}

通过看SpringBootServletInitializer类注释

/**
 * An opinionated {@link WebApplicationInitializer} to run a {@link SpringApplication}
 * from a traditional WAR deployment. Binds {@link Servlet}, {@link Filter} and
 * {@link ServletContextInitializer} beans from the application context to the server.
 * <p>
 * To configure the application either override the
 * {@link #configure(SpringApplicationBuilder)} method (calling
 * {@link SpringApplicationBuilder#sources(Class...)}) or make the initializer itself a
 * {@code @Configuration}. If you are using {@link SpringBootServletInitializer} in
 * combination with other {@link WebApplicationInitializer WebApplicationInitializers} you
 * might also want to add an {@code @Ordered} annotation to configure a specific startup
 * order.
 * <p>
 * Note that a WebApplicationInitializer is only needed if you are building a war file and
 * deploying it. If you prefer to run an embedded web server then you won't need this at
 * all.
 *
 * @author Dave Syer
 * @author Phillip Webb
 * @author Andy Wilkinson
 * @since 2.0.0
 * @see #configure(SpringApplicationBuilder)
 */

大致的意思就是,如果你构建了一个WAR包,部署在外置的容器中,需要实现这个类,才能正常访问服务

总结

归根结底还是对Springboot不熟悉。以前大学的时候接触过一段时间SSH开发,各种xml配置漫天飞,现在一接触到Springboot省了很多配置文件,确实方便了很多

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值