You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在API的ResponseBody中返回消息?创建新增学生数据接口

学生数据录入接口实现方案

需求概述

创建POST请求接口/newStudent,用于录入学生数据,接口成功响应时返回包含"status":"OK"和"message":"Data Added"的JSON格式响应体。

请求体示例

{
  "name":"Shubham",
  "rollno":22,
  "studentid":1
}

预期响应示例

{
  "status":"OK",
  "message":"Data Added"
}

完整代码实现

1. 学生实体类(Student.java)

用于接收请求体中的学生数据:

public class Student {
    private String name;
    private int rollno;
    private int studentid;

    // 生成无参、全参构造方法
    // 生成getter和setter方法
}

2. 响应结果实体类(ApiResponse.java)

用于封装接口响应内容:

public class ApiResponse {
    private String status;
    private String message;

    public ApiResponse(String status, String message) {
        this.status = status;
        this.message = message;
    }

    // 生成getter和setter方法
}

3. 控制器实现(StudentController.java)

基于你提供的代码片段修改,实现接口逻辑:

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class StudentController {

    @PostMapping("/newStudent")
    @ResponseStatus(HttpStatus.OK)
    public ApiResponse addStudent(@RequestBody Student student) {
        // 此处可添加实际业务逻辑,比如调用Service层将学生数据存入数据库
        return new ApiResponse("OK", "Data Added");
    }
}

代码说明

  • @RestController:替代@Controller+@ResponseBody组合,自动将返回对象序列化为JSON响应体
  • @PostMapping("/newStudent"):指定接口为POST请求,路径为/newStudent
  • @RequestBody:将请求体的JSON数据自动绑定到Student对象中
  • @ResponseStatus(HttpStatus.OK):设置响应状态码为200 OK
  • 方法返回ApiResponse对象,会被自动序列化为预期的JSON格式响应

内容的提问来源于stack exchange,提问作者SHUBHAM SHARMA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 03:30:45