Demo project for Spring Boot 【1】spring-boot-starter【2】Building a RESTful Web Service

Create a Resource Representation Class
Now that you have set up the project and build system, you can create your web service.
Begin the process by thinking about service interactions.
The service will handle GET requests for /greeting, optionally with a name parameter in the query string. The GET request should return a 200 OK response with JSON in the body that represents a greeting. It should resemble the following output:
{
“id”: 1,
“content”: “Hello, World!”
}
The id field is a unique identifier for the greeting, and content is the textual representation of the greeting.
创建资源表示类
现在已经设置了项目并构建了系统,现在可以创建web服务了。
从考虑服务交互开始这个过程。
该服务将处理/greeting的GET请求,可以选择在查询字符串中使用name参数。GET请求应该返回一个200ok响应,在表示问候语的主体中包含JSON。它应该类似于以下输出:
{
“id”:1,
“content”:“你好,世界!”
}
id字段是问候语的唯一标识符,content是问候语的文本表示。

@RequestParam binds the value of the query string parameter name into the name parameter of the greeting() method. If the name parameter is absent in the request, the defaultValue of World is used.
The implementation of the method body creates and returns a new Greeting object with id and content attributes based on the next value from the counter and formats the given name by using the greeting template.
A key difference between a traditional MVC controller and the RESTful web service controller shown earlier is the way that the HTTP response body is created. Rather than relying on a view technology to perform server-side rendering of the greeting data to HTML, this RESTful web service controller populates and returns a Greeting object. The object data will be written directly to the HTTP response as JSON.
This code uses Spring @RestController annotation, which marks the class as a controller where every method returns a domain object instead of a view. It is shorthand for including both @Controller and @ResponseBody.
The Greeting object must be converted to JSON. Thanks to Spring’s HTTP message converter support, you need not do this conversion manually. Because Jackson 2 is on the classpath, Spring’s MappingJackson2HttpMessageConverter is automatically chosen to convert the Greeting instance to JSON.
@SpringBootApplication is a convenience annotation that adds all of the following:
@Configuration: Tags the class as a source of bean definitions for the application context.
@EnableAutoConfiguration: Tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings. For example, if spring-webmvc is on the classpath, this annotation flags the application as a web application and activates key behaviors, such as setting up a DispatcherServlet.
@ComponentScan: Tells Spring to look for other components, configurations, and services in the com/example package, letting it find the controllers.
The main() method uses Spring Boot’s SpringApplication.run() method to launch an application. Did you notice that there was not a single line of XML? There is no web.xml file, either. This web application is 100% pure Java and you did not have to deal with configuring any plumbing or infrastructure.

@RequestParam将查询字符串参数name的值绑定到greeting()方法的name参数中。如果请求中不存在name参数,则使用默认值World。
方法体的实现根据计数器中的下一个值创建并返回一个具有id和content属性的新Greeting对象,并使用Greeting模板格式化给定的名称。
传统MVC控制器和前面所示的restfulweb服务控制器之间的一个关键区别是HTTP响应主体的创建方式。这个restfulweb服务控制器填充并返回一个问候对象,而不是依赖于视图技术来执行问候数据到HTML的服务器端呈现。对象数据将作为JSON直接写入HTTP响应。
这段代码使用Spring@RestController注释,它将类标记为一个控制器,其中每个方法返回一个域对象而不是一个视图。它是包含@Controller和@ResponseBody的简写。
问候对象必须转换为JSON。多亏了Spring的HTTP消息转换器支持,您不需要手动进行这种转换。因为jackson2在类路径上,所以会自动选择Spring的MappingJackson2HttpMessageConverter将问候实例转换为JSON。
@SpringBootApplication是一个方便的注释,它添加了以下所有内容:
@配置:将类标记为应用程序上下文的bean定义源。
@EnableAutoConfiguration:告诉springboot根据类路径设置、其他bean和各种属性设置开始添加bean。例如,如果springwebmvc在类路径上,这个注释将应用程序标记为web应用程序并激活关键行为,例如设置一个DispatcherServlet。
@ComponentScan:告诉Spring在com/example包中查找其他组件、配置和服务,让它找到控制器。
main()方法使用springboot的SpringApplication.run()启动应用程序的方法。你注意到没有一行XML?没有web.xml文件文件,或者。这个web应用程序是100%纯Java的,您不需要配置任何管道或基础设施。
Demo project for Spring Boot 【1】spring-boot-starter【2】Building a RESTful Web Service_第1张图片

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;
	}
}
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));
	}
}
<?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>demo-RESTfulWebService1</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo-RESTfulWebService1</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>

Demo project for Spring Boot 【1】spring-boot-starter【2】Building a RESTful Web Service_第2张图片
Demo project for Spring Boot 【1】spring-boot-starter【2】Building a RESTful Web Service_第3张图片
在这里插入图片描述

你可能感兴趣的:(springboot)