p:commandButton不会打开带有更新的窗口

时间:2012-08-24 07:10:51

标签: ajax jsf user-interface primefaces jpa-2.0

我在我的Bean中生成一个exportList:

    public void exportExcel() throws WriteException {
    try {
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=\"hours.xls\";");
        OutputStream out = response.getOutputStream();

        WorkbookSettings ws = new WorkbookSettings();
        ws.setLocale(new Locale("de", "DE"));
        WritableWorkbook workbook = Workbook.createWorkbook(out, ws);
        WritableSheet sheet = workbook.createSheet("Sheet1", 0);
        sheet.addCell(new Label(0, 0, "ID", bold));
        int row = 1;
        for (Hour hour : this.listHours) {
            sheet.addCell(new Label(0, row, String.valueOf(hour.getId())));
            row++;
        }

        SheetFormatter.setOptimalColumnWidth(sheet);
        workbook.write();
        workbook.close();
        response.flushBuffer();
        context.responseComplete();
        context.addMessage(null, new FacesMessage("Liste Exportiert"));
    }
    catch (Exception e) {
    }
}

在我的页面中,我在p:commandButton

中调用方法
    <p:commandButton  value="#{msg.export}" update="growl"
                    immediate="true" action="#{hoursView.exportExcel()}" />

我的页面不会打开excel-List ...如果添加属性ajax =“false”它可以工作但是更新将不会执行...

有关信息,我的Bean是SessionScoped,如果这会产生一些差异

1 个答案:

答案 0 :(得分:2)

您的第一个错误是您尝试使用ajax下载文件。那是不可能的。 Ajax由JavaScript代码执行,由于安全原因,没有设施强制“另存为”对话和/或将检索到的响应写入本地磁盘文件系统。否则,这将打开各种令人讨厌的安全漏洞可能性的大门。

因此,使用ajax="false"是绝对必要的。

您的第二个错误是您尝试将不同的回复混合到一个响应中。那是不可能的。您只能返回文件下载或ajax更新,而不能同时返回两者。要检索两个不同的响应,您基本上需要让客户端发送两个不同的请求。您可以按如下方式处理:

  1. 让客户端向支持bean发送ajax请求。
  2. 让服务器在服务器的临时存储系统中创建并保存Excel文件,并生成一个唯一的URL,以便servlet可以访问它。
  3. 让服务器发送包含该消息和URL的ajax响应。
  4. 让客户端显示消息并在URL上调用新的GET请求。您可以使用window.location=url;让JavaScript在URL上调用新的GET请求。
相关问题