Difference between file download in JSP and JSF

Difference between file download in JSP and JSF

JSP:

For configuration the following code should be present in JSP scriplet or in Servlet

//In servlet or Scriplet

String site = new String("D:\\Temporary\\2013\\Feb\\0228\\ASP_Journals_Feb28_13-57.xls");
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site);   



JSF:

In jsp the download configuration will be performed in scriplet or in servlet

In jsf  we need to do those configuration using Backing bean,

//In Backing bean

        try
        {
            String filename = "U:\\Informs\\2013\\Tex\\0218\\Mnsc1690-REVISES\\mnsc1690-2au.pdf";   //Input File
            File file = new File(filename);
            InputStream fis = new FileInputStream(file);
            byte[] buf = new byte[(int)file.length()];                                                //Get the file size in buffer
            int offset = 0;
            int numRead = 0;
            while ((offset < buf.length) && ((numRead = fis.read(buf, offset, buf.length - offset)) >= 0)) //Get the content for output stream
            {
                offset += numRead;
            }
            fis.close();
           

           
            //Configure response view
            HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + filename + "");
           
            //Print the content to reponse page
            response.getOutputStream().write(buf);
            response.getOutputStream().flush();
            response.getOutputStream().close();
            FacesContext.getCurrentInstance().responseComplete();
        }
        catch(Exception  e)
        {
            e.printStackTrace();  //Catch Exception
        }

//In JSF page
       
        <h:form>
            <table align="center" style="margin-top: 200px;"    >
                <tr>
                    <td><h:commandButton type="submit"  value="View Me" action="#{country.viewFile}"/></td> 
                    //Country is bean class name and viewName is method name
                   
                </tr>
            </table>
            </h:form>

Comments