用于图像上传的jsf中的NullPointer异常

时间:2013-03-21 05:16:29

标签: java jsf file-upload

我在jsf中上传文件时遇到问题。我已经完成了以下代码ih jsf。

的index.xhtml(查看)

<h:panelGrid columns="2">

            <h:outputLabel for="userId">User Id</h:outputLabel>
            <h:inputText id="userId" value="#{controller.user.userName}" required="true">                
            </h:inputText>

            <h:outputLabel for="username">Username</h:outputLabel>
            <h:inputText id="username" value="#{controller.user.userId}" required="true">               
            </h:inputText>

            <h:outputLabel for="photo">Profile Picture</h:outputLabel>
            <t:inputFileUpload value="#{controller.user.photo}"  required="true">                
            </t:inputFileUpload>

       </h:panelGrid>

User.java(模型)

package com.profileapp.models;

import java.io.Serializable;
import org.apache.myfaces.custom.fileupload.UploadedFile;


public class User implements Serializable
{
    private String userId;
    private String userName;
    private UploadedFile photo;

    public User()
    {        
    }
    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public UploadedFile getPhoto() {
        return photo;
    }

    public void setPhoto(UploadedFile photo) {
        this.photo = photo;
    }    
}

UserController.java(控制器)

package com.profileapp.controllers;

import com.profileapp.models.User;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import org.apache.commons.io.FilenameUtils;


@ManagedBean(name="controller")
@RequestScoped

public class UserController implements Serializable
{
    private User user=new User();   

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String submit() throws IOException ,SQLException ,ClassNotFoundException, InstantiationException, IllegalAccessException
    {
        String fileName = FilenameUtils.getName(user.getPhoto().getName());
        byte[] bytes = user.getPhoto().getBytes();
        int index=fileName.indexOf('.');
        String extension=fileName.substring(index);
        File file;
        String path;
        path = "C:/Users/Manohar/Documents/NetBeansProjects/ProfileApplication/build/web/uploads/"+user.getUserName()+(float)Math.random()+"/";
        if(extension.equalsIgnoreCase(".jpg")||extension.equalsIgnoreCase(".jpeg")||extension.equalsIgnoreCase(".png")||extension.equalsIgnoreCase(".gif")||extension.equalsIgnoreCase(".tif"))
        {
            file=new File(path);      
            if(!file.exists())
            {
                file.mkdir();                
            }
            path=file+"/"+fileName;
            FileOutputStream outfile=new FileOutputStream(path);           
            outfile.write(bytes);
            outfile.close();  
            PreparedStatement stmt;            
            Connection connection;
            String url="jdbc:mysql://localhost:3306/userprofile";
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            connection = DriverManager.getConnection(url, "root", "mysql"); 
            stmt = connection.prepareStatement("insert into table_profile values('"+user.getUserName()+"','"+user.getUserId()+"','"+path+"')");                                 
            stmt.executeUpdate();
            connection.close(); 
            return "SUCCESS";
        }
        else
        {
            return "FAIL";
        }              
    }

}

当我运行此代码时,我获得了字段inputFileUpolad元素的nullpointer execption,即当我调试时,我观察到User.photo字段的setter方法未被调用

我收到以下错误(组件树)

<UIViewRoot id="j_id1" inView="true" locale="en_US" renderKitId="HTML_BASIC" rendered="true" transient="false" viewId="/index.xhtml">

    <?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml">

    <UIOutput id="j_idt4" inView="true" rendered="true" transient="false">

        <title>Facelet Title</title>

    </UIOutput>

    <UIOutput id="j_idt6" inView="true" rendered="true" transient="false">

        <HtmlForm enctype="application/x-www-form-urlencoded" id="j_idt7" inView="true" prependId="true" rendered="true" submitted="true" transient="false">

            <HtmlPanelGrid border="-2147483648" columns="2" id="j_idt8" inView="true" rendered="true" transient="false">

                <HtmlOutputLabel escape="true" for="userId" id="j_idt9" inView="true" rendered="true" transient="false">

                    User Id

                </HtmlOutputLabel>

                <HtmlInputText disabled="false" id="userId" immediate="false" inView="true" localValueSet="false" maxlength="-2147483648" readonly="false" rendered="true" required="true" size="-2147483648" transient="false" valid="true" value="manu"/>

                <HtmlOutputLabel escape="true" for="username" id="j_idt11" inView="true" rendered="true" transient="false">

                    Username

                </HtmlOutputLabel>

                <HtmlInputText disabled="false" id="username" immediate="false" inView="true" localValueSet="false" maxlength="-2147483648" readonly="false" rendered="true" required="true" size="-2147483648" transient="false" valid="true" value="manu"/>

                <HtmlOutputLabel escape="true" for="photo" id="j_idt13" inView="true" rendered="true" transient="false">

                    Profile Picture

                </HtmlOutputLabel>

                <HtmlInputFileUpload disabled="false" id="j_idt15" immediate="false" inView="true" localValueSet="false" maxlength="-2147483648" readonly="false" rendered="true" required="true" size="-2147483648" transient="false" valid="true"/>

            </HtmlPanelGrid>

            <HtmlCommandButton action="#{controller.submit()}" actionExpression="#{controller.submit()}" disabled="false" id="j_idt16" immediate="false" inView="true" readonly="false" rendered="true" transient="false" type="submit" value="Register"/>

        </HtmlForm>

    </UIOutput>

    </html>

</UIViewRoot>

1 个答案:

答案 0 :(得分:1)

您忘记将表单编码正确设置为multipart/form-data。 JSF组件树显示它使用默认值application/x-www-form-urlencoded

相应修复:

<h:form enctype="multipart/form-data">

默认表单enctype不支持文件上传。不要忘记按web.xml在{{1}}注册扩展名过滤器。否则,JSF将无法正确执行应用请求值阶段。

另见: