在jsf中用于图片上传的NullPointer异常



我在jsf中有一个文件上传问题。我已经用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元素,即,当我调试我观察到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>

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

修改如下:

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

默认的表单enctype即不支持文件上传。不要忘记按照手册在web.xml中注册扩展过滤器。否则,JSF将不能正确地执行应用请求值阶段。

参见:

  • JSF 2.0文件上传

相关内容

  • 没有找到相关文章

最新更新