0

私はJavaサーバーの顔に取り組んでいます。User.java クラスをモデルとして、UserController をコントローラーとして、index.xhtml,ViewProfile,xhtml をビューとして使用しました。次のコードをトレースしたところ、セッター メソッド set setUploadedFile(UploadedFile file){} が呼び出されていないことがわかりました。一方、他の 2 つのセッターは呼び出されており、NullPointerException が発生しています。理由は何ですか ?私は得ていません。ここにコードがあります

ユーザーコントローラー.java

@Named("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.getUploadedFile().getName());
        byte[] bytes = user.getUploadedFile().getBytes();
        int index=fileName.indexOf('.');
        String extension=fileName.substring(index);
        File file;
        String path;
        path = "C:/Users/";
        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";
        }              
    }
}

ユーザー.java

import org.apache.myfaces.custom.fileupload.UploadedFile;


public class User implements java.io.Serializable
{    
    private String userName;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        System.out.println("in setter of username");
        this.userName = userName;
    }

    private String userId;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
        System.out.println("in setter of userid");
    }

    private UploadedFile uploadedFile;

    public UploadedFile getUploadedFile()
    {
        return uploadedFile;
    }

    public void setUploadedFile(UploadedFile uploadedFile) 
    {
        this.uploadedFile = uploadedFile;
        System.out.println("in setter of upload");
    }
}

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 lang="en"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:t="http://myfaces.apache.org/tomahawk">

    <h:head>
        <title>Profile Demo</title>        
    </h:head>
    <h:body>

        <h:form>
            <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.uploadedFile}"  required="true"></t:inputFileUpload>

               <h:commandButton value="Register" action="#{controller.submit()}"></h:commandButton>            
          </h:panelGrid> 
        </h:form>

    </h:body> 

</html>
4

1 に答える 1

2
<h:form>

ここで、適切なフォーム エンコーディング タイプを設定するのを忘れています。

デフォルトは ですapplication/x-www-form-urlencoded。したがって、すべてのリクエスト パラメータの名前と値がクエリ文字列形式で送信されることを意味します (これは基本的にString! です)。アップロードされたファイルの場合、ファイルの内容ではなく、ファイル名のみが送信されます。そのため、コンクリートが得られなくなりますFile

適切なフォーム エンコーディング タイプを設定する必要があります。

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

このように、リクエスト パラメータの名前と値は、ファイル コンテンツなどのバイナリ データを囲むことができる、より柔軟な別の形式で送信されます。ただし、標準の JSF はこの形式をサポートしていません。そのため、JSF が引き続きジョブを実行できるように、それを解析して通常の要求パラメーターに変換できるサーブレット フィルターを登録する必要があります。

<filter>
    <filter-name>MyFacesExtensionsFilter</filter-name>
    <filter-class>org.apache.myfaces.webapp.filter.ExtensionsFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>MyFacesExtensionsFilter</filter-name>
    <servlet-name>Faces Servlet</servlet-name>
</filter-mapping>

以下も参照してください。

于 2013-01-25T12:58:03.030 に答える