# 构建 RESTful Web 服务 本指南将引导您完成使用 Spring 创建“Hello, World” RESTful Web项目。 ## 你将开发什么 您将开发一个HTTP服务,可以接收如下GET 请求:`http://localhost:8080/greeting`。 它将以JSON格式返回值响应请求,如以下清单所示: ``` {"id":1,"content":"Hello, World!"} ``` 您可以在请求链接中使用`name`参数发送请求,如以下清单所示: ``` http://localhost:8080/greeting?name=User ``` 请求返回报文中,`name`参数值将覆盖默认值`World`,如下所示: ``` {"id":1,"content":"Hello, User!"} ``` ## 你需要什么 - 约15分钟 - 最喜欢的文本编辑器或IDE - [JDK 1.8](http://www.oracle.com/technetwork/java/javase/downloads/index.html)或更高版本 - [Gradle 4+](http://www.gradle.org/downloads)或[Maven 3.2+](https://maven.apache.org/download.cgi) - 您还可以将代码直接导入 IDE: - [Spring 工具套件 (STS)](https://spring.io/guides/gs/sts) - [IntelliJ IDEA](https://spring.io/guides/gs/intellij-idea/) ## 如何完成本指南 像大多数 Spring[入门指南](https://spring.io/guides)一样,您可以从头开始并完成每个步骤,也可以绕过您已经熟悉的基本设置步骤。无论哪种方式,您最终都会获得可用的代码。 要**从头开始**,请跳转到[从 Spring Initializr 开始](https://spring.io/guides/gs/rest-service/#scratch)。 要**跳过基础知识**,请执行以下操作: - [下载](https://github.com/spring-guides/gs-rest-service/archive/main.zip)并解压缩本指南的源存储库,或使用[Git](https://spring.io/understanding/Git) Clone:`git clone https://github.com/spring-guides/gs-rest-service.git` - cd into `gs-rest-service/initial` - 继续[创建资源表示类](https://spring.io/guides/gs/rest-service/#initial)。 **完成后**,您可以从如下目录查看结果代码 `gs-rest-service/complete`。 ## 从 Spring Initializr 开始 您可以使用这个[预先初始化的项目](https://start.spring.io/#!type=maven-project&language=java&platformVersion=2.5.5&packaging=jar&jvmVersion=11&groupId=com.example&artifactId=rest-service&name=rest-service&description=Demo project for Spring Boot&packageName=com.example.rest-service&dependencies=web)并单击 Generate 下载 ZIP 文件。此项目配置兼容本教程中的示例。 手动初始化项目: 1. 导航到[https://start.spring.io](https://start.spring.io/)。该服务提取应用程序所需的所有依赖项,并为您完成大部分设置。 2. 选择 Gradle 或 Maven 以及您要使用的开发语言。本指南假定您选择了 Java。 3. 单击**Dependencies**并选择**Spring Web**。 4. 单击**生成**。 5. 下载生成的 ZIP 文件,该文件是根据您的选择配置的 Web 应用程序的存档。 ``` 如果您的 IDE 具有 Spring Initializr 集成,您可以从您的 IDE 完成此过程。 ``` ``` 你也可以从 Github 上 fork 项目并在你的 IDE 或其他编辑器中打开它。 ``` ## 创建资源表示类 现在您已经设置了项目和构建系统,您可以创建您的 Web 服务。 首先考虑服务交互流程。 该服务将处理访问`/greeting`的`GET`请求,请求可选参数 `name`。该`GET`请求在返回`200 OK`的情况下,JSON返回值如下: ``` { "id": 1, "content": "Hello, World!" } ``` 该`id`字段是返回内容的唯一标识符,是返回内容`content`的文本表示。 要对返回内容建模,请创建一个资源表示类。为此,需要创建一个普通的Java 对象,其中包含`id`和`content`两个数据字段、构造函数和访问器,如以下(来自`src/main/java/com/example/restservice/Greeting.java`)所示: ``` package com.example.restservice; public class Greeting { private final long id; private final String content; public Greeting(long id, String content) { this.id = id; this.content = content; } public long getId() { return id; } public String getContent() { return content; } } ``` 此应用程序使用[Jackson JSON](https://github.com/FasterXML/jackson)库,将实例`Greeting`转换为JSON。web启动器默认包含Jackson。 ## 创建资源控制器 在 Spring 构建的 RESTful Web 服务中,HTTP 请求由控制器处理。这些组件由[`@RestController`](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RestController.html)注释标识,如下 `GreetingController`实例(参看 `src/main/java/com/example/restservice/GreetingController.java`)处理`GET`请求:`/greeting` ``` package com.example.restservice; import java.util.concurrent.atomic.AtomicLong; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class GreetingController { private static final String template = "Hello, %s!"; private final AtomicLong counter = new AtomicLong(); @GetMapping("/greeting") public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) { return new Greeting(counter.incrementAndGet(), String.format(template, name)); } } ``` 这个控制器简洁明了,但底层有很多事情要做。我们一步一步分解。 `@GetMapping`注解确保 HTTP GET 请求`/greeting` 可以映射到`greeting()`方法。 ``` 还有其他 HTTP 请求注解(例如`@PostMapping`POST)。所有注解均继承`@RequestMapping`,同时也可以使用如下注解方式(例如`@RequestMapping(method=GET)`)。 ``` `@RequestParam`将查询参数`name`的值绑定到方法`greeting()`的参数`name`上。如果请求中没有`name`参数,则使用参数默认值 `World`。 此方法创建并返回一个新`Greeting`对象,该对象包含`id`和`content`属性,并通过counter.incrementAndGet(), String.format(template, name) 分别进行参数赋值 传统 MVC 控制器和前面显示的 RESTful Web 服务控制器之间的一个关键区别是 HTTP 请求响应的创建方式。这个 RESTful Web 服务控制器不是依靠视图技术直接返回HTML类型的响应内容,而是填充并返回一个`Greeting`对象。对象数据将以 JSON 类型直接写入 HTTP 响应。 此代码使用 Spring[`@RestController`](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RestController.html)注解,它将类标记为控制器,其中每个方法都返回域对象而不是视图。它是`@Controller`和`@ResponseBody`的简写。 该`Greeting`对象必须转换为 JSON 格式。依赖于 Spring 的 HTTP 消息转换器支持,您无需手动进行此转换。因为classpath里面已经包含[Jackson 2](https://github.com/FasterXML/jackson),所以会自动选择Spring的[`MappingJackson2HttpMessageConverter`](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/http/converter/json/MappingJackson2HttpMessageConverter.html)将`Greeting`实例转换为JSON格式。 `@SpringBootApplication`是一个方便的注释,它包含了以下所有内容: - `@Configuration`: 在应用程序上下文中,将类标记为bean。 - `@EnableAutoConfiguration`:告诉 Spring Boot 根据类路径设置、其他 bean 和各种属性设置扫描并添加bean。例如,如果`spring-webmvc`位于类路径上,则此注释将应用程序标记为 Web 应用程序并激活关键行为,例如设置`DispatcherServlet`. - `@ComponentScan`: 告诉 Spring 在包`com/example`中扫描其他components, configurations及services类 该`main()`方法使用 Spring Boot 的`SpringApplication.run()`方法来启动应用程序。您是否注意到我们没有配置一行 XML?也没有`web.xml`文件。这个 Web 应用程序是 100% 纯 Java,您不必处理任何管道或基础设施的配置。 ### 构建一个可执行的 JAR 您可以使用 Gradle 或 Maven 从命令行运行应用程序。您还可以构建一个包含所有必要依赖项、类和资源的单个可执行 JAR 文件并运行它。构建可执行 jar 可以在整个开发生命周期、跨不同环境等中轻松地作为应用程序交付、版本化和部署服务。 如果您使用 Gradle,则可以使用`./gradlew bootRun`. 或者,您可以使用构建 JAR 文件`./gradlew build`,然后运行 JAR 文件,如下所示: ``` java -jar build/libs/gs-rest-service-0.1.0.jar ``` 如果您使用 Maven,则可以使用`./mvnw spring-boot:run`. 或者,您可以使用构建 JAR 文件,`./mvnw clean package`然后运行该 JAR 文件,如下所示: ``` java -jar target/gs-rest-service-0.1.0.jar ``` 此处描述的步骤创建了一个可运行的 JAR。您还可以[构建经典的 WAR 文件](https://spring.io/guides/gs/convert-jar-to-war/)。 该服务会在几秒钟内启动并运行。 ## 测试服务 现在服务已经启动,访问`http://localhost:8080/greeting`,您应该会看到: ``` {"id":1,"content":"Hello, World!"} ``` 通过访问提供`name`查询字符串参数`http://localhost:8080/greeting?name=User`。`content`请注意属性的值如何从`Hello, World!`变为`Hello, User!`,如以下所示: ``` {"id":2,"content":"Hello, User!"} ``` 这一变化表明,`@RequestParam`在`GreetingController`按预期工作。该`name`参数的默认值`World` 已被参数`name`的值覆盖 还要注意`id`属性是如何从`1`变为 的`2`。这证明是使用同一个`GreetingController`处理多个请求,并且其`counter`字段在每次调用时都按预期递增。 ## 概括 恭喜!您刚刚使用 Spring 开发了一个 RESTful Web 服务。 原文链接: https://spring.io/guides/gs/rest-service/