Thursday, March 8, 2012

File down with JSF applications

This note summarises different ways to implement file download with JSF applications.

Approach 1- File down using Servlet

This approach uses a servlet to serve file download request and the link to the servlet can be implemented by using various JSF components, e.g. commandLink and outputLink.

The servlet based approach is a simply and easy way to implement file down, however, the shortcoming here is the file serving process is outside the JSF life cycle, glue code is required when the download process needs to access JSF faces context and backing beans.

A detailed discussion of the approach can be found from here.

Approach 2- File down using JSF PhaseListener

This approach use a JSF PhaseListener to serving process, an example of such implementation can be found from the Mojarra Scales project, which provides a UI component that renders the download link and a PhaseListener that serves file content, sample usage is shown in below.

<sc:download id="downloadPdf" 
 method="download" 
 mimeType="application/pdf" 
 fileName="sample.pdf" 
 data="#{testBean.pdf}" 
 text="Download here">
</sc:download>

When the Mojarra Scales download component is used to create a download link, it renders a http link on the page with a specific URL format which the PhaseListener is used to identify the file request, once the link is clicked, the PhaseListener serves content in the beforePhase method at the RESTORE_VIEW phase.

By using a JSF PhaseListener, the file serving process is now part of the JSF lifecycle. However, the shortcoming here is the data for download is populated during page render, i.e. the evaluation of the #{testBean.pdf} expression in the above example, even the user has NOT click the download click.

Approach 3- File down using JSF Action/ActionListener

This approach use JSF Action/ActionListener that attaches to JSF commandLink or commandButton to serves file content.

Details discussion on Action based implementation can be found here, ActionListener based implementation can be found from the PrimeFaces FileDownload component.

This is the best approach from my point of view.

No comments:

Post a Comment