本文介绍如何用 Spring boot 构建一个简单的 Restful Web 服务。
实现什么功能
以 HTTP GET 方式访问 http://localhost:8080/greeting, 返回
{"id":1,"content":"Hello, World!"}
访问http://localhost:8080/greeting?name=User, 返回
{"id":1,"content":"Hello, User!"}
环境准备
- JDK 1.8 +
- Gradle 4 + or Maven 3.2+
- IntelliJ IDEA
创建 Spring boot 项目
社区版的 IDEA 可以参考 《社区版 IntelliJ IDEA 如何创建Spring boot项目》
旗舰版的 IDEA 可以参考《IntelliJ IDEA Ultimate ( 旗舰版 ) 如何创建Spring boot项目》
创建资源展现类
这个类是用来描述服务响应所包含的字段和类型。
src/main/java/com/example/demo/restservice/Greeting.java 代码如下:
package com.example.demo.restservice;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.atomic.AtomicLong;
@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));
}
}
创建资源控制器
在 Spring boot 中创建 Restful Web 服务,使用控制器来处理 HTTP 请求, 需要用到 @RestController 注解。
src/main/java/com/example/demo/restservice/GreetingController.java
代码:
package com.example.demo.restservice;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.atomic.AtomicLong;
@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() 函数上方,意思是: 访问 /greeting 的 HTTP GET请求 由 greeting() 函数处理。
@RequestParam,用于接收 HTTP GET请求 传过来的 name 值,默认值为 “World”