1 从官网获取所需框架的zip压缩包
采用 start.spring.io创建一个“网络”项目。在“依赖项”对话框中搜索并添加“web”依赖项,如屏幕截图所示。点击“生成”按钮,下载 zip,然后将其解压到计算机上的文件夹中。
2 修改应用文件代码
在 IDE 中打开项目并在DemoApplication.java文件src/main/java/com/example/demo夹中找到该文件。现在通过添加下面代码中显示的额外方法和注释来更改文件的内容。您可以复制并粘贴代码或直接输入。
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@GetMapping("/hello")
public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
return String.format("Hello %s!", name);
}
}
hello()我们添加的方法旨在采用名为 的 String 参数name,然后将此参数与"Hello"代码中的单词组合。这意味着如果您“Amy”在请求中将您的姓名设置为,则响应将为“Hello Amy”。
该@RestController注解告诉Spring,这个代码描述应该可在网上的端点。该@GetMapping(“/hello”)告诉Spring使用我们的hello()方法来回答这个问题被发送到请求http://localhost:8080/hello的地址。最后,@RequestParam告诉 Springname在请求中期望一个值,但如果它不存在,它将默认使用单词“World”。
3 运行应用程序
让我们构建并运行程序。打开命令行(或终端)并导航到项目文件所在的文件夹。我们可以通过发出以下命令来构建和运行应用程序:
MacOS/Linux:
- ./mvnw spring-boot:run
Windows:
- mvnw spring-boot:run
You should see some output that looks very similar to this:
这里的最后几行告诉我们 Spring 已经开始。Spring Boot 的嵌入式 Apache Tomcat 服务器充当网络服务器并侦听localhost端口上的请求8080。打开浏览器并在顶部的地址栏中输入http://localhost:8080/hello. 你应该得到这样一个友好的回应:
附:工程文件目录