h:commandButton action method is not invoked

295 views Asked by At

I have the below button:

<h:commandButton value="Download" action="#{listFiles.downloadFile}" />

And the below action method:

public void downloadFile()
    {
        // Some code.
    }

But when I press the button nothing happens. The action method is not invoked.

In the server log I see:

The form component needs to have a UIForm in its ancestry. Suggestion: enclose the necessary components within <h:form>

1

There are 1 answers

4
Ömer Faruk Kurt On BEST ANSWER

this work for me

My file in folder path

WEB-INF\pages\forms

cod in xhtml file

<h:commandLink value="Download" action="#{formBean.downloadFile('FileName.doc')}" styleClass="link"/>

beans

public String downloadFile(String fileName) {
        try {
            FacesContext facesContext = FacesContext.getCurrentInstance();
            HttpServletResponse response = ((HttpServletResponse) facesContext.getExternalContext().getResponse());
            String reportPath = facesContext.getExternalContext().getRealPath("\\pages\\forms") + File.separator + fileName;

            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName+ "\"");

            File file = new File(reportPath);

            BufferedInputStream bIn = new BufferedInputStream(new FileInputStream(file));

            int rLength = -1;

            byte[] buffer = new byte[1000];

            while ((rLength = bIn.read(buffer, 0, 100)) != -1) {
                response.getOutputStream().write(buffer, 0, rLength);
            }

            FacesContext.getCurrentInstance().responseComplete();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }