How to download a file using JSF 2 action

Today we have an interesting use case for you. Our sample JSF 2 application displays a PDF file after button is clicked. We have prepared an example action code which downloads PDF file from a given URL ( and displays it’s contents as the browser response to the button click. Here is how it works.

JSF 2 download file - Sample application - Click the Download PDF button to open PDF document

JSF 2 download file – Sample application – Click the Download PDF button to open PDF document

Our sample application project structure looks like this:

JSF 2 download file - Eclipse project structure

JSF 2 download file – Eclipse project structure

Here is the code.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
<html xmlns=""
        <title>JSF2 - download PDF after button click</title>
    		<h2>Click button to download PDF file</h2>
    		<h:commandButton id="button" value="Download PDF" action="#{downloadBean.downloadPdf}"/>

This is our sample application’s view. It contains only the commandButton component which calls downloadBean.downloadPdf action. When this button is clicked PDF document is displayed in the browser.


package com.itcuties.examples.webapps;


import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;

public class DownloadBean implements Serializable {

	private static final long serialVersionUID = 626953318628565053L;
	// A PDF to download
	private static final String PDF_URL = "";
	 * This method reads PDF from the URL and writes it back as a response. 
	 * @throws IOException 
	public void downloadPdf() throws IOException {
		// Get the FacesContext
		FacesContext facesContext = FacesContext.getCurrentInstance();
		// Get HTTP response
		HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
		// Set response headers
		response.reset();	// Reset the response in the first place
        response.setHeader("Content-Type", "application/pdf");	// Set only the content type
		// Open response output stream
		OutputStream responseOutputStream = response.getOutputStream();
		// Read PDF contents
		URL url = new URL(PDF_URL);
        InputStream pdfInputStream = url.openStream();
        // Read PDF contents and write them to the output
        byte[] bytesBuffer = new byte[2048];
        int bytesRead;
        while ((bytesRead = > 0) {
        	responseOutputStream.write(bytesBuffer, 0, bytesRead);
        // Make sure that everything is out
        // Close both streams
        // JSF doc: 
        // Signal the JavaServer Faces implementation that the HTTP response for this request has already been generated 
        // (such as an HTTP redirect), and that the request processing lifecycle should be terminated
        // as soon as the current phase is completed.

Here is the heart of our sample solution – downloadPdf method of the DownloadBean class. At the beginning of the code we obtain the HttpServletResponse object. Next we need to set Content-Type header of the response to application/pdf because we are returning the PDF contents as the response. Next step is to obtain the OutputStream object. Now we are ready to write response data to it.
Next PDF file bytes are being read the same way we have shown you in the Java Download file tutorial some time ago. PDF bytes are being read in the while loop and written to the response OutputStream.
After the streams are closed there is one important thing to do. You need to signal the JSF that the HTTP response for this request has been generated. You do that by calling the FacesContext.responseComplete() method.


 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "" >

  <display-name>JSF 2 - download PDF after the button is clicked</display-name>

	<!-- Welcome page -->

	<!-- Staring JSF -->
		<servlet-name>Faces Servlet</servlet-name>

	<!-- JSF URL mapping -->
		<servlet-name>Faces Servlet</servlet-name>

This is the standard configuration of the JSF framework that we use in our tutorials. JSF servlet is configured to load when application starts and mapped to all the *.xhtml URLs of the application. Welcome file is set to the index.xhtml page.


<project xmlns="" xmlns:xsi=""
	<name>jsf2-download-pdf Maven Webapp</name>
		<!-- JSF 2 API -->
		<!-- Servlet API -->

This is our maven configuration for this project.

Download this sample code here.

This code is available on our GitHub repository as well.

6 Responses to "How to download a file using JSF 2 action"

  1. Matthew says:

    Does the solution really depend on the pom.xml and web.xml configuration?
    Also, what if I want to download a .zip file?
    Would I have to rewrite

    response.setHeader("Content-Type", "application/pdf");


    response.setHeader("Content-Type", "application/zip");

    I tried your code but it did not exactly work:

    10:12:35,147 SEVERE [application]
            at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(
            at com.sun.faces.application.ActionListenerImpl.processAction(
            at javax.faces.component.UICommand.broadcast(
            at org.ajax4jsf.component.AjaxViewRoot.processEvents(

    The thing is, I create the file

    on the fly, and then want to make it available for downloading. Do I need to set some permissions or something? Like would chmod 600 filename be enough?


    • itcuties says:

      The file is not there, your JBoss is throwing 404.
      HTTP Status 404 - /bioinvindex/gene_data_download/filea/filea_ge.txt

  2. Lance says:

    Nice example, but the target file name is taken from the last qualifier (ViewFileFetch.jsf) in my case. How do I change the file name the browser will use when it saves the file?


    • Lance says:

      Ah, I forgot my old servlet skills. The answer is to set the “Content-Disposition” in the response header. In my case:

      response.setHeader("Content-Disposition", "attachment;filename=" + argPath.getFileName());
  3. Sergej says:

    Great tutorial, thank you! You really saved my day))

  4. Ashish Bhosle says:

    Kindly replace J2EE with JEE.
    J2EE is no longer in use.


Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply to Ashish Bhosle Cancel reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>