2015-05-14 88 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

相關問題