Spring Boot 如何在Resposne Body中返回消息?

wztqucjr  于 2022-11-23  发布在  Spring
关注(0)|答案(5)|浏览(185)

输入学生数据/newStudent时,我必须在ResponseBody的API中返回消息“数据已添加”。创建一个API
请求正文:

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

回应:
第一次

kjthegm6

kjthegm61#

您可以创建如下所示的自定义响应类:

class CustomResponse {
   private String status;
   private String message;
   // Constructor/Getters/Setters
}

然后在控制器中返回ResponseEntity,例如:

CustomResponse response = new CustomResponse("OK", "Data Added");
return ResponseEntity.ok(response); // the ok will return HTTP Status 200

或者,如果您需要另一个HttpStatus,则可以使用例如:

return new ResponseEntity<>(response, HttpStatus.CREATED);
                                      ^^^^^^^^^^^^^^^^^^
7cwmlq89

7cwmlq892#

这是如何在响应中返回自定义对象。

router.post("/newStudent", async (req, res) => {
  const { name, rollNo, studentId } = req.data;

  // POST data to DB
  const result = await AddStudentDataToDB({ name, rollNo, studentId });

  res.status(200).json({
    status: 'ok',
    message: 'Data Added'
  });
});
nsc4cvqm

nsc4cvqm3#

首先,您应该创建一个Response类,它将保存状态代码和自定义消息,如以下类:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Response {
  private String statusCode;
  private String statusMsg;
}

因此,在你的控制器中,使用ResponseEntity来发布对象,它允许你定制HTTP响应方法。例如:

@Autowired
 private StudentRepository studentRepository;

 @PostMapping("/newStudent")
 public ResponseEntity<Response> saveEmployee(@RequestBody Student 
  student){
    studentRepository.save(student);
    Response response = new Response();
    response.setStatusCode("200");
    response.setStatusMsg("Your message");
    return ResponseEntity.status(HttpStatus.CREATED).body(response);
}
polkgigr

polkgigr4#

import org.json.simple.JSONObject;

@ResponseBody
@RequestMapping(value = "/studentdata", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public String message(@RequestBody String transaction) {
  String response = "";

  JSONObject obj = new JSONObject();
  obj.put("status", "OK");
  obj.put("message", "Data Added");
  response = obj.toJSONString();
  
  return response;
}
ss2ws0br

ss2ws0br5#

在React课上,我的做法是这样的:

public class Response {
    private String statusCode;
    private String statusMsg;

    public String getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(String statusCode) {
        this.statusCode = statusCode;
    }

    public String getStatusMsg() {
        return statusMsg;
    }

    public void setStatusMsg(String statusMsg) {
        this.statusMsg = statusMsg;
    }
}

在控制器中:

@PostMapping("/newStudent")
    public ResponseEntity<Response> saveStudent(@RequestBody Student student) {
        Student save = service.save(student);
        Response response = new Response();
        response.setStatusCode("200");
        response.setStatusMsg("Data Added");
        return ResponseEntity.status(HttpStatus.CREATED).body(response);
    }

相关问题