Spring-构建 RESTful 网络服务

Spring initializr 配置

https://start.spring.io
添加 Web 依赖即可,其余配置随意。

创建 Greeting 类

要发送的消息格式为:

1
2
3
4
{
"id": 1,
"content": "Hello, World!"
}

包括一个数字类型 id 和 一个字符串类型的 content,因此按照如下创建 Greeting 类来代表要发送的消息。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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;
}
}

注:包括在 web starter 的 Jackson JSON 库会自动将 Greeting 类转换成 json 格式。

编写 Controller 处理 http 请求

编写 GreetingController

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.example.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));
}
}

RESTful web service controller 与传统 MVC controller 的不同是 HTTP 响应的创建方式。
RestController 会直接返回对象实例 (而不像传统 MVC 那样依赖于 view technology),Jackson JSON 库自动将 Greeting 实例转换成 json 格式的文本。

创建可执行文件 JAR

使用 gradle

  • 直接运行:./gradlew bootRun
  • 创建 jar 包:./gradlew build

使用 maven

  • 直接运行:./mvnw spring-boot:run
  • 创建 jar 包:./mvnw clean package

运行 jar 包

java -jar target/rest-service-0.0.1-SNAPSHOT.jar

测试创建的 service

访问 http://localhost:8080/greeting,将会看到

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

添加 name 参数的 http 请求, http://localhost:8080/greeting?name=User,将会看到

1
{"id":2,"content":"Hello, User!"}
打赏
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2022 qusong
  • 访问人数: | 浏览次数:

请我喝杯咖啡吧~

支付宝
微信