1、案例介紹:
1.1結構:
1.2 pom.xml:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
.....................................................
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
1.3 Controller層代碼:
@RestController
public class TestController {
@GetMapping(value = "/")
public String test1() {
return "hello world";
}
@GetMapping(value = "/test")
public Map<String, Object> test() {
Map<String, Object> map = new HashMap<>();
map.put("張三", 1);
map.put("李四", 2);
return map;
}
}
1.4 spring boot的啓動類
@SpringBootApplication
public 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
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
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;
@SpringBootApplication
public 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 #項目名