【问题标题】:Cannot call getWriter(), getOutputStream() already called [duplicate]无法调用 getWriter(),getOutputStream() 已调用 [重复]
【发布时间】:2015-03-24 06:35:33
【问题描述】:

我有一个使用 spring mvc 的程序。我写了两个控制器,第一个用于导入数据,第二个用于生成报告。我在生成控制器时遇到问题。当用户单击生成按钮时,我想生成报告,将报告保存在服务器硬盘上并将报告发送给用户。当我试图在硬盘上保存报告时,我遇到了非法状态异常:无法调用 getWriter(),getOutputStream() 已调用。我搜索了解决方案,但找不到匹配的答案。这是我的发电机控制器代码:

@RequestMapping(value = "/generate", method = RequestMethod.POST)
public String generateReport(
        Model model,
        @Valid @ModelAttribute("reportProperties") ReportProperties reportProperties,
        BindingResult result, HttpServletResponse response) {
    if (result.hasErrors()) {
        model.addAttribute("logMessage",
                "Generowanie Raportu nie powiodlo sie.");
        return "import";
    }

    //Walidacja dat. Mozna przeniesc na validator
    if(reportProperties.getEndDate().compareTo(reportProperties.getStartDate()) < 0){
        model.addAttribute("logMessage", "Data końcowa jest wcześniejsza od poprzedniej");
        return "import";
    }

    XSSFWorkbook report = null;
    if (reportProperties.getReportType().equalsIgnoreCase("tv")) {
        report = tvReportGenerator.generate(reportProperties);
    } else if (reportProperties.getReportType().equalsIgnoreCase("prod")) {
        report = prodReportGenerator.generate(reportProperties);
    } else {
        report = totalReportGenerator.generate(reportProperties);
    }
    if (report != null) {
        saveReportOnHardDrive(report);
        sendReportToUser(report, response);
    } else {
        model.addAttribute("logMessage",
                "Generowanie Raportu nie powiodlo sie.");
    }
    return "import";
}

private void saveReportOnHardDrive(XSSFWorkbook report) {
    try {
        Resource resource = new ClassPathResource("/general.properties");
        Properties props = PropertiesLoaderUtils.loadProperties(resource);
        String path = props.getProperty("saveFilePath");
        FileOutputStream out = new FileOutputStream(new File(path
                + new Date() + ".xlsx"));
        report.write(out);
        out.close();
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}

private void sendReportToUser(XSSFWorkbook report,
        HttpServletResponse response) {
    try {
        response.setContentType("application/xlsx");
        response.setHeader("Content-Disposition",
                "attachment; filename=generate.xlsx");
        report.write(response.getOutputStream());
        response.flushBuffer();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

我尝试了一些关闭和刷新响应 OutputStream 的解决方案,但没有奏效。 这是我的 import.jsp 文件:

<body>

<div id="Container">

<h1>Mediaplany GigaShopping <a href="/GigaShopping/resources/szablony/Instrukcja.pdf" target="_blank">instrukcja</a></h1>

<h2>Import Mediaplanu   <a href="/GigaShopping/resources/szablony/MediaplanSzablon.xlsx">pobierz szablon</a></h2>

<form method="POST" enctype="multipart/form-data"
    action="/GigaShopping/importMediaplan">
            <input type="file" name="mediaplanFile"/>
            <input type="submit" value="Prześlij plik"/>
</form>

<h2>Import cennika <a href="/GigaShopping/resources/szablony/CennikSzablon.xlsx" >pobierz szablon</a><a href="/GigaShopping/pricelist" style="margin-right: 4px;">aktualny cennik</a></h2>

<form method="POST" enctype="multipart/form-data"
    action="/GigaShopping/importPriceList"> 
    <input type="file" name="pricelistFile">
    <input type="submit" value="Prześlij plik">
</form>

<h2>Generowanie raportów</h2>

<form:form method="POST" action="/GigaShopping/generate" commandName="reportProperties">
    <table>
        <tr>
            <td>Typ raportu:</td>
            <td>
                <label><form:radiobutton path="reportType" value="tv"/> M/S TV</label>
                <label><form:radiobutton path="reportType" value="prod"/> M/S PROD</label>
                <label><form:radiobutton path="reportType" value="total"/> M/S TOTAL</label>
            </td>
        </tr>
        <tr>
            <td>Stacja</td>
            <td>
                <form:select path="tvName">
                    <form:options items="${televisionsList}"/>
                </form:select>
            </td>
        </tr>
        <tr>
            <td>Od</td>
            <td><form:input type="date" path="startDate" id="startDatePicker"/></td>
        </tr>   
        <tr>
            <td>Do</td>
            <td><form:input type="date" path="endDate" id="endDatePicker"/></td>
        </tr>
        <tr>
            <td colspan="2"><input type="submit" value="Generuj"></td>
        </tr>
    </table>
</form:form>

<form:form method="POST" action="/GigaShopping/requestDBContent" commandName="requestProperties">
    <form:input type="date" id="requestDatePicker" path="date"/>
    <form:select path="tvName">
        <form:option value="wszystkie">--wszystkie--</form:option>
        <form:options items="${televisionsList}"/>
    </form:select>      
    <input value="zobacz mediaplan" type="submit" name="requestMediaplanButton" />
    <input value="zobacz zamówienia" type="submit" name="requestOrdersButton"/>                     
</form:form>

<span class="logMessage">${logMessage}</span>

<footer>
    <a href="http://cns.com.pl">CNS 2015</a>
</footer>

</div>

感谢您的帮助。 问候, 塞巴提安

【问题讨论】:

  • 不是重现问题的最短代码。
  • 请添加堆栈跟踪。
  • 您不能将文件发送到客户端,然后再转发到页面,在写入文件后您必须使用return null 而不是return import
  • 抱歉,我忘记添加堆栈跟踪,但 M. Deinum 解决了这个问题。非常感谢!

标签: java spring jsp spring-mvc servlets


【解决方案1】:

作为@M。德努姆说

您必须返回 null 而不是您尝试转发的页面名称..

【讨论】:

    猜你喜欢
    • 2018-03-25
    • 2012-07-13
    • 2015-09-15
    • 1970-01-01
    • 2016-03-16
    • 1970-01-01
    • 1970-01-01
    • 2015-10-30
    • 2019-10-10
    相关资源
    最近更新 更多