Spring Boot ResponseEntity
最后修改于 2023 年 7 月 16 日
Spring Boot ResponseEntity教程展示了如何在Spring应用中使用ResponseEntity。
Spring 是一个流行的 Java 应用程序框架,而 Spring Boot 是 Spring 的一个演进,它有助于轻松创建独立的、生产级的基于 Spring 的应用程序。
ResponseEntity
ResponseEntity 代表一个HTTP响应,包括头部、主体和状态码。虽然 @ResponseBody 将返回值放入响应主体中,但 ResponseEntity 还可以让我们添加头部和状态码。
Groovy 示例
我们展示了一些使用ResponseEntity类创建响应的控制器方法。
package com.zetcode
@RestController
class MyApp {
@GetMapping("/status")
ResponseEntity<String> home() {
ResponseEntity.status(HttpStatus.OK).body("OK")
}
@GetMapping("/notfound")
ResponseEntity<String> notfound() {
ResponseEntity.notFound().build()
}
@GetMapping("/badrequest")
ResponseEntity<String> badRequest() {
ResponseEntity.badRequest().body("Bad request")
}
}
该示例展示了如何创建常见的OK、未找到和错误请求状态响应。
$ curl -i localhost:8080/status HTTP/1.1 200 Content-Type: text/plain;charset=UTF-8 Content-Length: 2 Date: Sun, 22 May 2022 21:11:20 GMT
$ curl -i localhost:8080/notfound HTTP/1.1 404 Content-Length: 0 Date: Sun, 22 May 2022 21:11:51 GMT
$ curl -i localhost:8080/badrequest HTTP/1.1 400 Content-Type: text/plain;charset=UTF-8 Content-Length: 11 Date: Sun, 22 May 2022 21:12:15 GMT Connection: close
package com.zetcode
import java.time.LocalDate
import groovy.transform.Immutable
@Immutable
class User {
String name
String occupation
}
@RestController
class MyApp {
def users = [
new User('John Doe', 'gardener'),
new User('Roger Roe', 'driver'),
new User('Kim Smith', 'teacher'),
new User('Joe Nigel', 'artist'),
new User('Liam Strong', 'teacher'),
new User('Robert Young', 'gardener')
]
@GetMapping("/users")
ResponseEntity<User> home() {
ResponseEntity.ok().body(users)
}
@GetMapping("/random-user")
ResponseEntity<User> notfound() {
def rnd = new Random()
def ru = users.get(rnd.nextInt(users.size()))
ResponseEntity.ok().body(ru)
}
}
在该示例中,我们有两个URL路径,它们使用ResponseEntity发送用户列表和随机用户。
$ curl localhost:8080/random-user
{"name":"Roger Roe","occupation":"driver"}
$ curl localhost:8080/users
[{"name":"John Doe","occupation":"gardener"},
{"name":"Roger Roe","occupation":"driver"},
{"name":"Kim Smith","occupation":"teacher"},
{"name":"Joe Nigel","occupation":"artist"},
{"name":"Liam Strong","occupation":"teacher"},
{"name":"Robert Young","occupation":"gardener"}]
Spring Boot ResponseEntity 示例
在下面的应用程序中,我们演示了ResponseEntity的用法。该应用程序有两个方法:一个方法使用ResponseEntity创建HTTP响应,另一个使用@ResponseBody。
build.gradle
...
src
├── main
│ ├── java
│ │ └── com
│ │ └── zetcode
│ │ ├── Application.java
│ │ ├── controller
│ │ │ └── MyController.java
│ │ └── model
│ │ └── Country.java
│ └── resources
│ └── static
│ └── index.html
└── test
├── java
└── resources
这是 Spring 应用程序的项目结构。
plugins {
id 'org.springframework.boot' version '3.1.1'
id 'io.spring.dependency-management' version '1.1.0'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
}
这是 Gradle 构建文件。 spring-boot-starter-web 是使用 Spring MVC 创建 Spring Boot Web 应用程序的依赖项。
package com.zetcode.model;
import java.util.Objects;
public class Country {
private String name;
private int population;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPopulation() {
return population;
}
public void setPopulation(int population) {
this.population = population;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Country country = (Country) o;
return population == country.population && Objects.equals(name, country.name);
}
@Override
public int hashCode() {
return Objects.hash(name, population);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Country{");
sb.append("name='").append(name).append('\'');
sb.append(", population=").append(population);
sb.append('}');
return sb.toString();
}
}
这是 Country Bean。它有两个属性:name 和 population。
package com.zetcode.controller;
import com.zetcode.model.Country;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MyController {
@RequestMapping(value = "/getCountry")
public ResponseEntity<Country> getCountry() {
var c = new Country();
c.setName("France");
c.setPopulation(66984000);
var headers = new HttpHeaders();
headers.add("Responded", "MyController");
return ResponseEntity.accepted().headers(headers).body(c);
}
@RequestMapping(value = "/getCountry2")
@ResponseBody
public Country getCountry2() {
var c = new Country();
c.setName("France");
c.setPopulation(66984000);
return c;
}
}
控制器包含两种方法。第一种方法使用ResponseEntity,第二种方法使用@ResponseBody。
@RequestMapping(value = "/getCountry")
public ResponseEntity<Country> getCountry() {
getCountry 方法映射到 getCountry URL 模式;它返回类型为 Country 的 ResponseEntity。
var c = new Country();
c.setName("France");
c.setPopulation(66984000);
我们创建一个 Country Bean;该 Bean 在响应中返回。
var headers = new HttpHeaders();
headers.add("Responded", "MyController");
我们创建一个 HttpHeaders 实例并添加一个新的标头值。
return ResponseEntity.accepted().headers(headers).body(c);
返回一个 ResponseEntity。我们为 ResponseEntity 提供自定义状态码、标头和主体。
@RequestMapping(value = "/getCountry2")
@ResponseBody
public Country getCountry2() {
var c = new Country();
c.setName("France");
c.setPopulation(66984000);
return c;
}
使用 @ResponseBody,只返回主体。标头和状态码由 Spring 提供。
<!DOCTYPE html>
<html>
<head>
<title>Home page</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<p>
<a href="getCountry">Get country 1</a>
</p>
<p>
<a href="getCountry2">Get country 2</a>
</p>
</body>
</html>
这是主页。它包含两个链接。
package com.zetcode;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Application 是设置 Spring Boot 应用程序的入口点。
$ curl localhost:8080/getCountry -I HTTP/1.1 202 Responded: MyController Content-Type: application/json Transfer-Encoding: chunked Date: Sat, 14 May 2022 10:48:33 GMT
当调用第一个方法时,我们可以看到选择的 202 状态码和自定义标头值。
在本文中,我们展示了如何在 Spring Boot 应用程序中使用 ResponseEntity。