springboot打war包后部署到tomcat后访问返回404错误


springboot打war包后部署到tomcat后访问返回404错误

1、正常情况下,修改打包方式为war

<packaging>war</packaging>

 


2、启动类继承SpringBootServletInitializer,重写configure方法

@SpringBootApplication
public class SmallProgramApplication extends SpringBootServletInitializer {

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(SmallProgramApplication.class);
}

public static void main(String[] args) {
SpringApplication.run(SmallProgramApplication.class, args);
}
}

 

 

 

 

 

 

 

我因为添加了servlet,在启动类实现了ServletContextInitializer,并重写了onStartup方法,把servlet加进来

@SpringBootApplication
public class SmallProgramApplication extends SpringBootServletInitializer implements ServletContextInitializer {

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(SmallProgramApplication.class);
}

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
servletContext.addServlet(WeiXinServlet.class.getSimpleName(),new WeiXinServlet())//
.addMapping("/wx");
}

public static void main(String[] args) {
SpringApplication.run(SmallProgramApplication.class, args);
}
}

 

 

 

 

 

 

 

 



结果是:在idea启动访问正常,打war包后,tomcat启动正常,但看不到springboot启动日志,能访问servlet,但不能访问controller
我个人判断出现这种原因的可能是:
重写onStartup方法,将SpringBootServletInitializer中的springboot的onStartup方法覆盖,所以导致springboot没有成功启动。

因为这个坑了很久,所以记录下来。

如要自定义servlet或过滤器,拦截器等,有三种方式:

1、使用注解形式

@WebServlet("/wx")
public class WeixinServlet extends HttpServlet {
  ......
}
在启动类上加注解:@ServletComponentScan
打war包后,可以访问servlet和controller

2、使用配置bean形式

 servlet类上不使用注解

public class WeixinServlet extends HttpServlet {
  …………。
}

   新建一个配置类,并使用注解:@Configuration

@Configuration
public class WebConfig {
@Bean
public ServletRegistrationBean servletRegistration(){
return new ServletRegistrationBean(new WeixinServlet(),"/wx");
}
}

   在配置类内添加如上内容,打war包后可以访问 "/wx"和其它controller

3、实现接口ServletContextInitializer,并实现其方法onstart

    该方式不推荐使用,打war包后,不能正常访问,有时springboot不能启动。

 

 

 





免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM