1、先启动好
参考我的spring boot学习第一篇文档:spring boot 1.5.x版本启动接口服务_veminhe的博客-CSDN博客
需要改动2个地方
pom.xml里面
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
启动后,发现使用http://localhost:8080/demo/api
访问不行
访问http://localhost:8080/api
却是好的。
无意中看到阿里云开发者平台资料
Spring 全家桶之 Spring Boot 2.6.4(二)- Configuration(Part B)(下)-阿里云开发者社区
注意观察Tomcat started on port(s): 8080 (http) with context path '/demo'这样的启动日志
配置工程上下文根的配置,应该是server.servlet.context-path=/demo这样的,改了后,重启服务
访问http://localhost:8080/demo/api
接口正常
2、贴上代码
2.1pom.xml文件内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.hmblogs</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<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>
</dependency>
</dependencies>
</project>
2.2application.properties文件内容如下:
server.port=8080
server.servlet.context-path=/demo
2.3HelloController.java文件内容如下:
package com.example.demo;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
@RestController
public class HelloController {
@RequestMapping("/api")
public String index() {
return "Greetings from Spring Boot!";
}
}
2.4DemoApplication.java文件内容如下:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}