Spring Boot ResponseEntity 教程展示了如何在 Spring 应用中使用ResponseEntity
。
Spring 是流行的 Java 应用框架,而 Spring Boot 是 Spring 的演进,可以帮助轻松地创建独立的,生产级的基于 Spring 的应用。
ResponseEntity
ResponseEntity
代表 HTTP 响应,包括标头,正文和状态。 尽管@ResponseBody
将返回值放入响应的正文中,但是ResponseEntity
也允许我们添加标头和状态代码。
Spring Boot ResponseEntity
示例
在以下应用中,我们演示ResponseEntity
的用法。 该应用有两种方法:一种方法使用ResponseEntity
创建 HTTP 响应,另一种方法@ResponseBody
。
这是 Spring 应用的项目结构。
pom.xml
这是 Maven pom.xml
文件。 spring-boot-starter-parent
是父 POM,它为使用 Maven 构建的应用提供依赖关系和插件管理。 spring-boot-starter-web
是使用 Spring MVC 创建 Spring Boot Web 应用的依赖项。 spring-boot-maven-plugin
将 Spring 应用打包到可执行的 JAR 或 WAR 归档文件中。
com/zetcode/model/Country.java
这是Country
bean。 它具有两个属性:name
和population
。
com/zetcode/controller/MyController.java
控制器包含两种方法。 第一个使用ResponseEntity
,第二个使用@ResponseBody
。
getCountry()
方法映射到getCountry
URL 模式; 它返回类型为Country
的ResponseEntity
。
我们创建一个Country
bean; 此 bean 在响应中返回。
我们创建HttpHeaders
的实例并添加新的标头值。
返回ResponseEntity
。 我们给ResponseEntity
一个自定义状态代码,标头和正文。
使用@ResponseBody
,仅返回正文。 标题和状态代码由 Spring 提供。
resources/static/index.html
这是主页。 它包含两个链接。
com/zetcode/Application.java
Application
是设置 Spring Boot 应用的入口。
调用第一个方法时,我们可以看到选择的 202 状态代码和自定义标头值。
在本教程中,我们展示了如何在 Spring 应用中使用ResponseEntity
。