4

我在后端生成了一个 PDF 文档。我想使用 Spring MVC REST 框架返回它。MarshallingView 和 ContentNegotiatingViewResolver 应该是什么样的?

根据我找到的示例,控制器将返回以下内容:

return new ModelAndView(XML_VIEW_NAME, "object", 
    byteArrayResponseContainingThePDFDocument);

-谢谢你。

4

1 回答 1

16

您可以通过以下方式定义您的方法以显式接收HttpServletRequestHttpServletResponse直接流式传输到 HttpServletResponse:

@RequestMapping(value="/pdfmethod", produces="application/pdf")
public void pdfMethod(HttpServletRequest request, HttpServletResponse response){
    response.setContentType("application/pdf");
    InputStream inputStream = null;
    OutputStream outputStream = null;
    try{
        inputStream = getInputStreamFromYourPdfFile();
        outputStream = response.getOutputStream();
        IOUtils.copy(inputStream, outputStream);
    }catch(IOException ioException){
        //Do something or propagate up..
    }finally{
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(outputStream);
    }
}
于 2012-08-03T22:41:25.273 回答