2015-05-14 103 views
0

我想使控制器中的方法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

有什么问题?

回答

0

你可以这样做:

@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) 

两个工作正常。

+0

user'responseEntity'而不是'ModelAndView'?第二种解决方案不起作用 – lapots

+0

那么'ResponseEntity'工作正常。毕竟,你正在进行http调用。 – mtyurt

0

什么是FileProcessUtils?谷歌不会提出任何事情。这是由您或您的组织创建的课程吗?看起来该方法正在返回一个应用程序/ json的内容类型的响应。你期待它回归什么?为什么?您必须以某种方式解析json以提取构建ModelAndView所需的数据,或者找到返回所需内容的另一种方法。

但是没有关于FileProcessUtils的更多信息,不可能提供更多的答案。

+0

'FileProcessUtils'只是我自己的工具类。基本上在这种情况下,只需调用'return new String(file.getBytes())'。我期待返回'json',但似乎ie9有一些问题需要处理 – lapots

+0

那么这就是问题所在。您可能需要将RequestMapping注释的“产生”子句移到那里,因为您向我们显示的代码中没有任何内容将此信息传输到FileProcessUtils.processFileUploading()。 –

+0

对不起。我不明白。将注释移动到工具类的目的是什么? – lapots

相关问题