我正在尝试映射一个页面请求以同时返回一个 View 和一个 JSON 对象。为此,我使用了 Jackson JSON 提供程序
这是我的 Controller 方法
@RequestMapping(method = RequestMethod.GET, value = "/reports")
public String getFiles(Model model) {
//
//build array list
//
return files;
}
这会很好地返回我的 View (WEB-INF/jsp/reports.jsp
),但是没有 Jackson 构建的 JSON 对象,所以我当然需要用 @ 注释该方法ResponseBody
会自动将 JSON 对象写入 http 响应,并返回 files
ArrayList...
@RequestMapping(method = RequestMethod.GET, value = "/reports")
@ResponseBody
public ArrayList<String> getFiles(Model model) {
//
///build array list
//
return files;
}
并且确实返回了 JSON 对象,但是在新 View /空白 html 文档中。是否可以返回 JSON 对象并同时重定向到“reports.jsp”?
最佳答案
我假设在您的第一个示例中您实际上返回的是 "reports"
而不是 files
。如果你想返回一个 View ,你不能同时返回一个响应体——你只能返回一个东西。
因此,要么将其拆分为两个请求,要么将 JSON 放入模型中,然后在 JSP 中检索它,例如
Java:
ObjectMapper mapper = new ObjectMapper();
model.addAttribute("json", mapper.writeValueAsString(files));
JSP:
<script>
var files=${json};
</script>
关于java - Spring Controller 一起返回 View 和 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29401844/