spring - 当我还必须为 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
}
解决方案
您不需要返回 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”;
}
推荐阅读
- javascript - 突出显示 div 中的特定字符串
- c# - 如何创建可以生成自己的字段和新面板的 ASP.NET C#?
- python - 使用循环连接数据框的列 - Python
- javascript - 将几个文本字段中的值传递到第三个(生成用户名)HTML、JS
- android - Android Studio:生成主 dex 列表时出错
- javascript - 使用 Node.js 重命名文件
- html - 由于某种原因,我的 scss 文件不会加载到 github html 页面上
- java - 如何在 Java 中检查 Integer 的泛型类型“T”?
- gradle - 如何通过 Gradle 任务运行 JMeter GUI?
- python - 如何在 csv 文件中使用 panda 中的条件?