Spring 3.0 Java REST返回PDF文档 [英] Spring 3.0 Java REST return PDF document

查看:445
本文介绍了Spring 3.0 Java REST返回PDF文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a PDF document generated in the backend. I want to return this using Spring MVC REST framework. What should the MarshallingView and ContentNegotiatingViewResolver look like?

根据我找到的样本,控制器将此作为回报:

Based on a sample I found, the controller would have this as the return:

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

- 谢谢你。

推荐答案

您可以定义您的方法以接受显式的 HttpServletRequest HttpServletResponse 并流式传输到HttpServletResponse直接,这样:

You can define your method to take in explicit HttpServletRequest and HttpServletResponse and stream to the HttpServletResponse directly, this way:

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

这篇关于Spring 3.0 Java REST返回PDF文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆