第 5 章 配置 GreetingController 以返回 JSON 响应


设置 Spring Web 示例时自动生成的 GreetingController 是一个简单的端点,它将文本字符串返回为响应。在更复杂的应用程序中,您可能需要配置 REST 控制器,以 JSON 格式返回响应。以下示例演示了如何配置 Spring RestController 以返回 JSON 内容:

流程

  1. 展开 GreetingController 类,如示例所示。扩展类返回 JSON 格式的响应,其中包含问候和名称。请注意,您必须从 Spring Web 导入 PathVariable 注解类,以确保您的配置正常工作:

    src/main/java/org/acme/spring/web/GreetingController.java

    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping("/greeting")
    public class GreetingController {
    
        @GetMapping
        public String hello() {
            return "hello";
        }
    
        @GetMapping("/{name}")
        public Greeting hello(@PathVariable(name = "name") String name) {
            return new Greeting("hello " + name);
        }
    
        public static class Greeting {
            private final String message;
    
            public Greeting(String message) {
                this.message = message;
            }
    
            public String getMessage(){
                return message;
            }
        }
    }
    Copy to Clipboard Toggle word wrap

  1. 当您更改 REST 端点时,还必须更新包含 REST 端点的单元测试的类文件:

    src/test/java/org/acme/spring/web/GreetingControllerTest.java

    package org.acme.spring.web;
    
    import io.quarkus.test.junit.QuarkusTest;
    import org.junit.jupiter.api.Test;
    
    import static io.restassured.RestAssured.given;
    import static org.hamcrest.CoreMatchers.is;
    
    @QuarkusTest
    public class GreetingControllerTest {
    
        @Test
        public void testHelloEndpoint() {
            given()
              .when().get("/greeting/quarkus")
              .then()
                .statusCode(200)
                .body("message", is("hello quarkus"));
        }
    
    }
    Copy to Clipboard Toggle word wrap

    请注意,当您在 Quarkus 中使用 Spring Web 兼容性层时,com.fasterxml:jackson.core 依赖项会自动添加到应用程序的 classpath 中,并配置。

Red Hat logoGithubredditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

通过我们的产品和服务,以及可以信赖的内容,帮助红帽用户创新并实现他们的目标。 了解我们当前的更新.

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

Theme

© 2026 Red Hat
返回顶部