添加 sayHello() 方法,并包含所有必要的注解和导入,使文件看起来像这样:
package com.example.springboottutorial;
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 SpringBootTutorialApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootTutorialApplication.class, args);
}
@GetMapping("/hello")
public String sayHello(@RequestParam(value = "myName", defaultValue = "World") String name) {
return String.format("Hello %s!", name);
}
}
sayHello() 方法接受 名称 参数,并返回与参数值组合的词 您好。 所有其他事务都通过添加 Spring 注释来处理:
@RestController 注解将 SpringBootTutorialApplication 类标记为请求处理程序(REST 控制器)。
@GetMapping("/hello") 注解将 sayHello() 方法映射到针对 /hello 的 GET 请求。
@RequestParam 注解将 名称 方法参数映射到 myName Web 请求参数。 如果您在网络请求中不提供 myName 参数,它将默认为 世界。