users@glassfish.java.net

Uploading files with JSF

From: <glassfish_at_javadesktop.org>
Date: Tue, 01 Jul 2008 07:39:25 PDT

Hello, I need code that can perform a file upload with Glassfish, but I am having lots of problems. I know that JSF does not directly support file uploads, and third party software is required. I've been spending several days trying to get this to work, but so far it's been very frustrating.

At the moment I have some dummy HTML and JavaScript code to handle file uploads on a website. To see what I have, please go to http://phoenix.ens-lyon.fr/simulator/ , then click the "ISOCHRONE chi-squared fitting" button, then select "Other filter set" in the "Specify the photometric system" in the drop-down menu. An additional set of inputs is displayed allowing one or more files to be uploaded, but currently this does nothing.

Anyway, in a project called, say, uploadtest, I have the following files:

1) /uploadtest/src/java/com/csharp/MyBean.java:
package com.csharp;

import org.apache.myfaces.custom.fileupload.UploadedFile;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.*;

public class MyBean {
    private UploadedFile myFile;
    private String myParam;
    private String myResult;

    public UploadedFile getMyFile() {
        return myFile;
    }

    public void setMyFile(UploadedFile myFile) {
        this.myFile = myFile;
    }

    public String getMyParam() {
        return myParam;
    }

    public void setMyParam(String myParam) {
        this.myParam = myParam;
    }

    public String getMyResult() {
        return myResult;
    }

    public void setMyResult(String myResult) {
        this.myResult = myResult;
    }

    public String processMyFile() {
        try {
            MessageDigest md
                = MessageDigest.getInstance(myParam);
            InputStream in = new BufferedInputStream(
                myFile.getInputStream());
            try {
                byte[] buffer = new byte[64 * 1024];
                int count;
                while ((count = in.read(buffer)) > 0)
                    md.update(buffer, 0, count);
            } finally {
                in.close();
            }
            byte hash[] = md.digest();
            StringBuffer buf = new StringBuffer();
            for (int i = 0; i < hash.length; i++) {
                int b = hash[i] & 0xFF;
                int c = (b >> 4) & 0xF;
                c = c < 10 ? '0' + c : 'A' + c - 10;
                buf.append((char) c);
                c = b & 0xF;
                c = c < 10 ? '0' + c : 'A' + c - 10;
                buf.append((char) c);
            }
            myResult = buf.toString();
            return "OK";
        } catch (Exception x) {
            FacesMessage message = new FacesMessage(
                FacesMessage.SEVERITY_FATAL,
                x.getClass().getName(), x.getMessage());
            FacesContext.getCurrentInstance().addMessage(
                null, message);
            return null;
        }
    }
}

2) /uploadtest/web/index.html:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Refresh" content= "0; URL=index.faces"/>
<title>Start Web Application</title>
</head>
<body>
<p>Please wait for the web application to start.</p>
</body>
</html>

3) /uploadtest/web/index.jsp:
<jsp:forward page="MyForm.faces"/>

4) /uploadtest/web/MyForm.jsp:
<%@ page contentType="text/html" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://myfaces.apache.org/tomahawk" prefix="t" %>
<f:view>
<html>
<head>
<title>Test 2 of Uploading Files</title>
</head>
<body>
<h:form id="MyForm" enctype="multipart/form-data" >
    <h:messages globalOnly="true" styleClass="message"/>
    <h:panelGrid columns="3" border="0" cellspacing="5">
        <h:outputLabel for="myFileId" value="File: "/>
        <t:inputFileUpload id="myFileId"
            value="#{myBean.myFile}"
            storage="file"
            required="true"/>
        <h:message for="myFileId"/>
        <h:outputLabel for="myParamId" value="Param: "/>
        <h:selectOneMenu id="myParamId"
                value="#{myBean.myParam}"
                required="true">
            <f:selectItem itemLabel="" itemValue=""/>
            <f:selectItem itemLabel="MD5" itemValue="MD5"/>
            <f:selectItem itemLabel="SHA-1" itemValue="SHA-1"/>
            <f:selectItem itemLabel="SHA-256" itemValue="SHA-256"/>
            <f:selectItem itemLabel="SHA-384" itemValue="SHA-384"/>
            <f:selectItem itemLabel="SHA-512" itemValue="SHA-512"/>
        </h:selectOneMenu>
        <h:message for="myParamId"/>
        <h:outputText value=" "/>
        <h:commandButton value="Submit"
            action="#{myBean.processMyFile}"/>
        <h:outputText value=" "/>
    </h:panelGrid>
</h:form>
</body>
</html>
</f:view>

5) /uploadtest/web/MyResult.jsp:
<%@ page contentType="text/html"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<f:view>
<html>
<head>
<title>Test 2 of Uploading Files Results Page</title>
</head>
<body>
    <h:panelGrid columns="2" border="0" cellspacing="5">
        <h:outputText value="File Name:"/>
        <h:outputText value="#{myBean.myFile.name}"/>
        <h:outputText value="File Size:"/>
        <h:outputText value="#{myBean.myFile.size}"/>
        <h:outputText value="Param:"/>
        <h:outputText value="#{myBean.myParam}"/>
        <h:outputText value="Result:"/>
        <h:outputText value="#{myBean.myResult}"/>
    </h:panelGrid>
</body>
</html>
</f:view>

6) /uploadtest/web/WEB-INF/web.xml:
<?xml version="1.0"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
        version="2.5">
   <servlet>
      <servlet-name>Faces Servlet</servlet-name>
      <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
      <load-on-startup>1</load-on-startup>
   </servlet>
   <servlet-mapping>
      <servlet-name>Faces Servlet</servlet-name>
      <url-pattern>*.faces</url-pattern>
   </servlet-mapping>
   <welcome-file-list>
      <welcome-file>index.html</welcome-file>
   </welcome-file-list>
   <filter>
      <filter-name>MyFacesExtensionsFilter</filter-name>
      <filter-class>org.apache.myfaces.webapp.filter.ExtensionsFilter</filter-class>
      <init-param>
         <param-name>maxFileSize</param-name>
         <param-value>20m</param-value>
         <!--<description>Set the size limit for uploaded files.
            Format: 10 - 10 bytes
                    10k - 10 KB
                    10m - 10 MB
                    1g - 1 GB
         </description>-->
      </init-param>
   </filter>
   <filter-mapping>
      <filter-name>MyFacesExtensionsFilter</filter-name>
      <url-pattern>*.jsf</url-pattern>
   </filter-mapping>
</web-app>

The description tag caused and error so it had to be commented out.

7) /uploadtest/web/WEB-INF/faces-config.xml:
<?xml version="1.0"?>

<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
        http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd"
        version="1.2">
    <managed-bean>
        <managed-bean-name>myBean</managed-bean-name>
        <managed-bean-class>com.csharp.MyBean</managed-bean-class>
        <managed-bean-scope>request</managed-bean-scope>
    </managed-bean>
    <navigation-rule>
        <from-view-id>/MyForm.jsp</from-view-id>
        <navigation-case>
            <from-outcome>OK</from-outcome>
            <to-view-id>/MyResult.jsp</to-view-id>
        </navigation-case>
    </navigation-rule>
</faces-config>

After many attempts and failures I eventually have the following 7 jar files in
/uploadtest/web/WEB-INF/lib/:
commons-el-1.0.jar
commons-io-1.2.jar
jsf-api.jar
tomahawk-1.1.6.jar
commons-fileupload-1.1.jar
commons-logging-1.1.1.jar
jsf-impl.jar

I am sure this is more than necessary as some may be redundant, but the Java compiles successfully, and on deployment the HTML page is displayed briefly before a blank page is show. In look at the log I get the following warning messages:

Message ID: executePhase(RENDER_RESPONSE 6,com.sun.faces.context.FacesContextImpl_at_1b6847a) threw exception java.lang.NullPointerException at com.sun.faces.renderkit.RenderKitImpl.createResponseWriter(RenderKitImpl.java

Complete Message: 183) at com.sun.faces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:168) at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:106) at com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:251) at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:144) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:245) at....

followed by the severe messages:

Message ID: StandardWrapperValve[Faces Servlet]

Complete Message: PWC1406: Servlet.service() for servlet Faces Servlet threw exception java.lang.NullPointerException at com.sun.faces.renderkit.RenderKitImpl.createResponseWriter(RenderKitImpl.java:183) at com.sun.faces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:168) at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:106) at com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:251) at....

and would most appreciate some help. I am very frustrated as this has taken up several days, and I am on my own working in a French university with nobody around to help.

Incidentally, I've just noticed that the code in the Java file is not properly displayed on preview. It seems the hex codes confuses things, so ignore it and use the uploaded file.

Christopher Sharp

Christopher Sharp
[Message sent by forum member 'csharpdotcom' (csharpdotcom)]

http://forums.java.net/jive/thread.jspa?messageID=283644