springboot打war包后部署到tomcat后訪問返回404錯誤
1、正常情況下,修改打包方式為war
<packaging>war</packaging> |
2、啟動類繼承SpringBootServletInitializer,重寫configure方法
@SpringBootApplication |
我因為添加了servlet,在啟動類實現了ServletContextInitializer,並重寫了onStartup方法,把servlet加進來
@SpringBootApplication |
結果是:在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不能啟動。