知方号

知方号

springboot本地启动,访问路径正常,外部tomcat运行,接口访问404

springboot本地启动,访问路径正常,外部tomcat运行,接口访问404

1、案例介绍:   1.1结构:

   1.2 pom.xml: org.springframework.boot spring-boot-starter-parent 2.2.5.RELEASE ..................................................... 1.8 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test org.junit.vintage junit-vintage-engine     1.3 Controller层代码: @RestControllerpublic class TestController { @GetMapping(value = "/") public String test1() { return "hello world"; } @GetMapping(value = "/test") public Map test() { Map map = new HashMap(); map.put("张三", 1); map.put("李四", 2); return map; }} 1.4 spring boot的启动类 @SpringBootApplicationpublic class DebugDemoApplication{ public static void main(String[] args) { SpringApplication.run(DebugDemoApplication.class, args); }} 1.5 简述

application.yaml中任何配置。

很简单的spring boot demo而已。在本地用直接run启动。完全ok。

并且浏览器访问localhost:8080(这里application.yaml并未配置server.servlet. context-path),可以在浏览器看到

2、问题

        就是这个简单的demo在本地用idea中,run启动,完全没有任何问题,但是使用maven打包成war包,然后使用tomcat启动,再去访问localhost:8080/项目名 (ps:这里跟springboot中用内置tomcat运行,访问路径不太一样)。

       使用maven打完包后:demo-0.0.1-SNAPSHOT.war,将其改名demo.war丢到tomcat的webapps下。在bin目录中运行.status.bat运行tomcat。

访问浏览器localhost:8080/demo:

3.解决     3.1 引入spring-boot-starter-tomcat org.springframework.boot spring-boot-starter-tomcat provided    3.2 启动类 import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.builder.SpringApplicationBuilder;import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;@SpringBootApplicationpublic class DebugDemoApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(DebugDemoApplication.class, args); } @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(DebugDemoApplication.class); }}

以上修改完毕后,使用idea再次run启动,访问浏览器localhost:8080:

再次打包、重命名、并启动tomcat服务器,查看放在外部tomcat服务器中的效果:

所以,综上问题已解决。

ps:

       本地springboot启动与tomcat服务器启动访问的接口的路径不太一致,这里解决也很简单,在spring boot的主配置文件application.yml中添加一段配置:

server: servlet: context-path: /demo #项目名

 

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至lizi9903@foxmail.com举报,一经查实,本站将立刻删除。