首页 > 解决方案 > 当我还必须为 MVC 进程返回网页时,如何使用 Spring Rest MVC 返回响应正文?

问题描述

这是我的代码,我知道我不应该做 2 个返回语句,而只是为了解释我的问题。谢谢

@PostMapping
@ResponseStatus(HttpStatus.Created)
public String addStudent(@RequestBody Student student){
    return StudentRep.save(Student);// Should be PayLoad Client Response
    return “Student”; // Should be redirect to Student.html

}

标签: springrestmodel-view-controllerjax-rs

解决方案


您不需要返回 ResponseBody。您可以简单地将属性添加到您的模型,然后在您的视图中使用它们。

@PostMapping
@ResponseStatus(HttpStatus.Created)
public String addStudent(@RequestBody Student student, Model model){
    String id = StudentRep.save(Student);// Should be PayLoad Client Response
    model.addAttribute("studentId", id);
    // Will redirect to Student.html where you can use the id attribute.
    return “Student”; 
}

现在,如果您使用Thymeleaf,您可以在模板中的任何位置使用这个新属性。我不确定您是如何创建模板的,所以我只是用作Thymeleaf示例。

<p th:text=${id}></p>

现在,如果您想返回一个 Stundet 对象,您需要对控制器进行以下更改。

@PostMapping
@ResponseStatus(HttpStatus.Created)
public String addStudent(@RequestBody Student student, Model model){
    StudentRep.save(Student);// Should be PayLoad Client Response
    model.addAttribute("student", student);
    // Will redirect to Student.html where you can use the student attribute.
    return “Student”; 
}

推荐阅读