使用PrintWriter和OutputStream

Ran*_*dom 5 java servlets outputstream printwriter

我正在用struts创建一个项目,我在使用Jasper IReports时遇到了问题.我想将一些信息导出到pdf文件中并且我一直得到java.lang.IllegalStateException:getOutputStream()已被调用...由于在页面已打开PrintWriter时在我的代码中打开ServletOutputStream而导致异常.

代码在模型中(因此它不在jsp中,它在java文件中),如下所示:

    public void handle(HttpServletResponse res, Connection connection, String path)throws Exception{
    ServletOutputStream out = null;
    try {

        JasperDesign jasperDesign = JRXmlLoader.load(path);
        JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
        byte[] bytes = JasperRunManager.runReportToPdf(jasperReport, null, connection);
        res.setContentType("application/pdf");
        res.setContentLength(bytes.length);
        out = res.getOutputStream();
        out.write(bytes, 0, bytes.length);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        out.flush();
        out.close();
    }
Run Code Online (Sandbox Code Playgroud)

我检查了连接,路径和HttpServletResponse,都运行正常.

我是Jasper Reports的新手以及编写PDF格式的东西,所以你可以 - 正确地 - 我对我在这里做的事情有一点了解,显然我的代码是通过网络从某处复制/粘贴的.

我曾尝试使用PrintWriter而不是OutputStream,将字节转换为String并使用PrintWriter.append(String)方法(allthought不是String是CharSequence),但它不会将数据提取到PDF中.

我也尝试获取PrintWriter,关闭它以打开OutputStream(不起作用)或刷新它(两者都没有).

任何帮助解决方案使用任何可以显示pdf数据的解决方案都会很棒.非常感谢!

sim*_*ord 5

查看堆栈跟踪会很有用.

您可能首先尝试运行健全性检查:修改该代码以简单地将静态字符串(hello world)写入ServletOutputStream并将内容类型设置为text/html.因为这应该工作正常:

public void handle(HttpServletResponse res, Connection connection, String path)throws Exception{
ServletOutputStream out = null;
try {
    byte[] bytes = "hello world".getBytes();
    res.setContentType("text/html");
    res.setContentLength(bytes.length);
    out = res.getOutputStream();
    out.write(bytes, 0, bytes.length);
} catch (Exception e) {
    e.printStackTrace();
} finally {
    out.flush();
    out.close();
}
Run Code Online (Sandbox Code Playgroud)

HTH