代码之家  ›  专栏  ›  技术社区  ›  guerda

在加载时执行backingbean操作?

  •  9
  • guerda  · 技术社区  · 16 年前

    导出是在操作方法中完成的。我可以通过一个 commandButton 但它必须在加载时自动执行。

    我怎样才能做到这一点?

    JSF:

    <h:commandButton value="Download report" action="#{resultsView.downloadReport}"/>
    

    支持bean:

      public String downloadReport() {
        ...
        FileDownloadUtil.downloadContent(tmpReport, REPORT_FILENAME);
        // Stay on this page
        return null;
      }
    

    澄清:这对a4j是否可行?我想到了一个解决方案,Ajax请求触发我的 downloadReport 操作及其请求是文件下载。

    4 回复  |  直到 16 年前
        1
  •  15
  •   Dan Allen    16 年前

    只需创建一个下载视图(/download.xhtml),在呈现之前触发下载侦听器。

    <?xml version="1.0" encoding="UTF-8"?>
    <f:view
        xmlns="http://www.w3.org/1999/xhtml"
        xmlns:f="http://java.sun.com/jsf/core">
        <f:event type="preRenderView" listener="#{reportBean.download}"/>
    </f:view>
    

    然后,在报告bean(使用JSR-299定义)中,推送文件并将响应标记为完成。

    public @Named @RequestScoped class ReportBean {
    
       public void download() throws Exception {
          FacesContext ctx = FacesContext.getCurrentInstance();
          pushFile(
               ctx.getExternalContext(),
               "/path/to/a/pdf/file.pdf",
               "file.pdf"
          ); 
          ctx.responseComplete();
       }
    
       private void pushFile(ExternalContext extCtx,
             String fileName, String displayName) throws IOException {
          File f = new File(fileName);
          int length = 0; 
          OutputStream os = extCtx.getResponseOutputStream();
          String mimetype = extCtx.getMimeType(fileName);
    
          extCtx.setResponseContentType(
             (mimetype != null) ? mimetype : "application/octet-stream");
          extCtx.setResponseContentLength((int) f.length());
          extCtx.setResponseHeader("Content-Disposition",
             "attachment; filename=\"" + displayName + "\"");
    
          // Stream to the requester.
          byte[] bbuf = new byte[1024];
          DataInputStream in = new DataInputStream(new FileInputStream(f));
    
          while ((in != null) && ((length = in.read(bbuf)) != -1)) {
             os.write(bbuf, 0, length);
          }  
    
          in.close();
       }
    }
    

    您可以链接到下载页面(/download.jsf),或者在启动页面上使用HTML元标记重定向到该页面。

        2
  •  8
  •   Bozho    16 年前

    使用 <rich:jsFunction action="#{bean.action}" name="loadFunction" /> 然后window.onload=loadFunction;

        3
  •  3
  •   BalusC    16 年前

    window.onload = function() {
        document.formname.submit();
    }
    
        4
  •  0
  •   Ольга    7 年前

    使用事件

    <ui:composition 
                xmlns="http://www.w3.org/1999/xhtml"
                xmlns:ui="http://java.sun.com/jsf/facelets"
                xmlns:f="http://xmlns.jcp.org/jsf/core"
    >
       <f:event type="preRenderView" listener="#{beanName.method}"/>
       ...    
    </ui:composition>
    
    推荐文章