My blog has moved!

You should automatically be redirected in 6 seconds. If not, visit
http://blogs.i2m.dk/allan
and update your bookmarks.

Monday, 16 March 2009

Sending files through action listeners

For this weeks JSF tip, I’ll show you how to send binary data (such as a file) to the user by way of an action handler or listener.

Say, you want to generate a custom PDF and send it to the user as he clicks a link. You need a JSF page, and a backing bean.

Your JSF page may look like this:

<h:form>
    <h:commandLink id="lnkDownload"
                   actionListener="#{myBean.onDownload}"
                   target="_blank"
                   value="Download PDF"  />
</h:form>



Your JSF backing bean may look like this:
public MyBean {

    public void onDownload(ActionEvent event) {
         try {
            // here you need to get the byte[] representation of 
            // the file you want to send
            byte[] binary_data = ;
            String filename = "generated_file.pdf”;
            FacesContext fctx = FacesContext.getCurrentInstance();   
            ExternalContext ectx = fctx.getExternalContext();
            
            HttpServletResponse response = (HttpServletResponse) ectx.getResponse();
            response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
            response.setHeader("Content-Transfer-Encoding", "Binary");
            response.setHeader("Pragma", "private");
            response.setHeader("cache-control", "private, must-revalidate");
        
            ServletOutputStream outs = response.getOutputStream();
            outs.write(binary_data);
            outs.flush();
            outs.close();
            response.flushBuffer();
            
            fctx.responseComplete();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
}


That’s it for today.

P.S. alternatively you can use this component which is less code intensive: http://kenai.com/projects/scales/pages/Download

2 comments:

Anonymous said...

You can also use MyFaces Commons Exporter ;).

Allan Lykke Christensen said...

Please post a link to an example Hazem. Haven't been able to locate it on Google.

Thanks!