建立一个RESTful Web服务

原文链接:https://spring.io/guides/gs/rest-service/


这篇教程帮你体验用Spring创建一个“Hello, World” RESTful Web服务的过程。

你会创建什么

你将会创建一个在http://localhost:8080/greeting接收HTTP GET请求的服务。
它将会返回一个JSON格式的问候,就像下面一样:

{"id":1,"content":"Hello, World!"}

你可以通过在query string中提供一个可选的name参数来自定义问候语,就像下面一样:

http://localhost:8080/greeting?name=User

name参数值会覆盖默认的值World并且体现在响应中,就像下面一样:

{"id":1,"content":"Hello, User!"}

你需要什么

如何完成这篇指南

和大多数的Spring Getting Started guides非常像,你可以从头开始并完成每一步或者跳过你已经熟悉的基础步骤。无论哪一种,你最终都可以获得可以运行的代码。

如果想从头开始, 请移步Starting with Spring Initializr.

如果想跳过基础步骤,做以下步骤:

当你完成时,你可以在gs-rest-service/complete中查看对应你源代码的结果

从Spring Initializr开始

对于所有的Spring应用,你应该从Spring Initializr开始。这个Initializr提供了加入你项目所需的所有依赖的快速方法并且为你做了很多步骤。这个例子只需要Spring Web依赖。下方的图片展示了Initializr如何建立示例项目。使用Initializr建立项目
上面的图片展示了在Initializr中Maven被选作构建工具。你也可以使用Gradle。它还显示了com.examplerest-service各自作为Group和Artifact的值。你将会在剩余的示例中使用所选择的值。

下面的清单展示了你选择Maven时创建的pom.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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.2.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>rest-service</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>rest-service</name>
	<description>Demo project for Spring Boot</description>

	<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>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

下面的清单展示了你选择Gradle时创建的build.gradle文件:

plugins {
	id 'org.springframework.boot' version '2.3.2.RELEASE'
	id 'io.spring.dependency-management' version '1.0.8.RELEASE'
	id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
	mavenCentral()
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-web'
	testImplementation('org.springframework.boot:spring-boot-starter-test') {
		exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
	}
}

test {
	useJUnitPlatform()
}

建立一个Resource Representation类

鉴于你已经建立的项目且构建了系统,你可以创建你的Web服务了。

通过思考服务交互来开始这个过程。

这个服务将会处理发送至/greetingGET请求。其中在query string中的参数name是可选的。这个GET请求应该返回一个在响应体中有JSON格式问候与的200 OK响应。它应该看起来像下方的输出:

{
    "id": 1,
    "content": "Hello, World!"
}

id字段是一个欢迎的唯一标识符,content是代表欢迎的文字。

创建一个resource representation类来完成问候信息。为idcontent数据提供一个带有字段、构造器、访问器的POJO(Plain Old Java Object)。就像下面(文件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库来自动地把Greeting类型的实例转化为JSON。Jackson默认被包含在web starter中。

创建一个资源控制器

在Spring的创建RESTful web服务的方法中,HTTP请求在控制器中被处理。这些部件被@RestController注解所标记,并且如下所示的GreetingController(文件src/main/java/com/example/restservice/GreetingController.java)通过返回一个Greeting类的新实例来处理发送到/greetingGET请求。

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注解确保发送到/greeting的HTTP GET请求被映射到greeting()方法。

还有一些关于其他HTTP请求方法的注解(例如用于POST方法的@PostMapping)。这些注解都派生于@RequestMapping注解,并且该注解可以作为他们的同义词提供服务(例如@RequestMapping(method=GET))。

@RequestParam将query string中name参数的值绑定到greeting()方法的name参数中。如果name参数在请求中缺失,则defaultValue的值World将被使用。

函数体的实现创建并且返回了一个新的带有idcontent属性的Greeting对象。其中id基于变量counter的下一个值,content则是基于格式化后的给定name值的问候 template

传统MVC控制器与和刚才介绍的RESTful web服务的一个关键区别就是HTTP响应体的创建方式不同。RESTful web服务控制器产生并返回一个Greeting对象,而不是依赖于视图技术执行服务端渲染来将问候数据渲染到HTML。对象数据将以JSON格式直接写入HTTP响应。

这段代码使用Spring@RestController注解,它将类标记为控制器,在控制器中每个方法返回一个域对象而不是视图。它是联合使用@Controller@ResponseBody的简便写法。

这个Greeting对象必须被转换为JSON。得益于Spring的HTTP消息转换器的支持,你无需手动进行转换。由于Jackson 2在classpath中,Spring的MappingJackson2HttpMessageConverter被自动选中来将Greeting实例转换为JSON。

@SpringBootApplication是一个便捷的注解写法来添加下方所列的东西:

  • @Configuration:为应用上下文中标记这个类为bean定义的源。
  • @EnableAutoConfiguration:告诉Spring Boot开始键入基于classpath设置、其他beans和各种各样的属性设置。例如,如果spring-webmvc在classpath中,这个注解标记应用为一个Web应用并且激活关键行为,例如建立一个DispatcherServlet
  • @ComponentScan:告诉Spring在com/example包中寻找其他组件、配置和服务,让他找到控制器。

main()函数使用Spring Boot的SpringApplication.run()方法来启动应用。你注意到教程中一行XML也没有了吗?也没有web.xml文件。这个Web应用是百分百纯Java的,你不用处理高级或基础的配置。

构建可执行的JAR

你可以使用Gradle或者Maven从命令行运行应用。你也可以构建一个包含所有必需依赖、类和资源的单独的可执行JAR文件然后运行它。构建一个可执行的JAR文件使得项目在整个开发生命周期中,都可以将服务作为应用程序,在跨不同环境等等情况下轻松发布、版本化和部署。

如果你使用Gradle,你可以通过./gradlew bootRun运行应用。或者,你可以通过./gradlew build构建JAR文件然后运行它,如下所示:

java -jar build/libs/gs-rest-service-0.1.0.jar

如果你使用Maven,你可以通过./mvnw spring-boot:run运行应用.。或者,你可以通过./mvnw clean package构建JAR文件然后运行它,如下所示:

java -jar target/gs-rest-service-0.1.0.jar

这些步骤描述了创建可执行JAR的过程。你也可以构建一个传统的WAR文件

测试服务

鉴于服务可用,访问http://localhost:8080/greeting,在那里你应当看到:

{"id":1,"content":"Hello, World!"}

通过访问http://localhost:8080/greeting?name=User在query string中提供name参数。注意content的值从Hello, World!变成了Hello, User!,如下所示:

{"id":2,"content":"Hello, User!"}

这个变化证明在GreetingController@RequestParam注解的工作符合预期。name参数被给予一个默认值World但是可以可以通过query string显式覆盖。

也要注意id属性是如何从1变到2的。这证明您的多个请求针对同一个GreetingController进行操作。并且GreetingControllercounter字段正在按照预期地每次请求加一。

总结

恭喜!你刚刚通过Spring开发了一个RESTful web服务。

还可以看

The following guides may also be helpful:

  • Accessing GemFire Data with REST
  • Accessing MongoDB Data with REST
  • Accessing data with MySQL
  • Accessing JPA Data with REST
  • Accessing Neo4j Data with REST
  • Consuming a RESTful Web Service
  • Consuming a RESTful Web Service with AngularJS
  • Consuming a RESTful Web Service with jQuery
  • Consuming a RESTful Web Service with rest.js
  • Securing a Web Application
  • Building REST services with Spring
  • React.js and Spring Data REST
  • Building an Application with Spring Boot
  • Creating API Documentation with Restdocs
  • Enabling Cross Origin Requests for a RESTful Web Service
  • Building a Hypermedia-Driven RESTful Web Service
  • Circuit Breaker

Want to write a new guide or contribute to an existing one? Check out our contribution guidelines.

All guides are released with an ASLv2 license for the code, and an Attribution, NoDerivatives creative commons license for the writing.

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
restful restful所需要的jar包 ========================================= Restlet, a RESTful Web framework for Java ========================================= http://www.restlet.org ----------------------------------------- Native REST support * Core REST concepts have equivalent Java classes (UniformInterface, Resource, Representation, Connector for example). * Suitable for both client-side and server-side web applications. The innovation is that that it uses the same API, reducing the learning curve and the software footprint. * Restlet-GWT module available, letting you leverage the Restlet API from within any Web browser, without plugins. * Concept of "URIs as UI" supported based on the URI Templates standard. This results in a very flexible yet simple routing with automatic extraction of URI variables into request attributes. * Tunneling service lets browsers issue any HTTP method (PUT, DELETE, MOVE, etc.) through a simple HTTP POST. This service is transparent for Restlet applications. Complete Web Server * Static file serving similar to Apache HTTP Server, with metadata association based on file extensions. * Transparent content negotiation based on client preferences. * Conditional requests automatically supported for resources. * Remote edition of files based on PUT and DELETE methods (aka mini-WebDAV mode). * Decoder service transparently decodes compressed or encoded input representations. This service is transparent for Restlet applications. * Log service writes all accesses to your applications in a standard Web log file. The log format follows the W3C Extended Log File Format and is fully customizable. * Powerful URI based redirection support similar to Apache Rewrite module. Available Connectors * Multiple server HTTP connectors available, based on either Mortbay's Jetty or the Simple framework or Grizzly NIO framework. * AJP server connector available to let you plug behind an Apache HTT

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值