使mvc控制器返回文本,而不是json
问题描述:
我想使控制器中的方法Spring MVC方法返回text
而不是json
。使mvc控制器返回文本,而不是json
我现在的方法是这样的
@RequestMapping(value = "/upload", method = RequestMethod.POST, produces = "text/html")
public ModelAndView uploadFile(@RequestParam("file") MultipartFile file) {
LOGGER.debug("Attempt to upload file with template.");
try {
String fileContent = FileProcessUtils.processFileUploading(file);
return createSuccessResponse(fileContent);
} catch (UtilityException e) {
LOGGER.error("Failed to process file.", e.getWrappedException());
return createResponse(INTERNAL_ERROR_CODE, e.getMessage());
}
}
但响应头content-type: application/json
。
我试图通过HttpServletResponse
控制器和设置内容类型,但它仍然继续返回json
。
有什么问题?
答
你可以这样做:
@RequestMapping(value = "/foo", method = RequestMethod.GET)
public ResponseEntity foo() throws Exception {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("text/html"));
return ResponseEntity.ok().headers(headers).body("response");
}
或做到这一点:
@RequestMapping(value = "/foo", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
两个工作正常。
答
什么是FileProcessUtils?谷歌不会提出任何事情。这是由您或您的组织创建的课程吗?看起来该方法正在返回一个应用程序/ json的内容类型的响应。你期待它回归什么?为什么?您必须以某种方式解析json以提取构建ModelAndView所需的数据,或者找到返回所需内容的另一种方法。
但是没有关于FileProcessUtils的更多信息,不可能提供更多的答案。
user'responseEntity'而不是'ModelAndView'?第二种解决方案不起作用 – lapots
那么'ResponseEntity'工作正常。毕竟,你正在进行http调用。 – mtyurt