不在 JSF 中调用 setter 方法



我正在研究Java服务器面。 我使用User.java类作为模型,UserController作为控制器和索引.xhtml,ViewProfile,xhtml作为视图。 我跟踪了以下代码,我观察到setter方法set setUploadedFile(UploadedFile file){}不调用.而其他两个setter正在调用.并且它给出了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");
    }
}

索引.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>
<h:form>

在这里,您忘记设置正确的表单编码类型。

默认值为 application/x-www-form-urlencoded,这意味着所有请求参数名称和值都以查询字符串格式发送(本质上是一个String!对于上传的文件,只会发送文件名,而不会发送文件内容。这就是为什么你最终没有得到具体的File.

您需要设置正确的表单编码类型。

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

这样,请求参数名称和值以不同且更灵活的格式发送,允许包含二进制数据,例如文件内容。但是,标准 JSF 不支持这种格式,这就是为什么您需要注册一个 servlet 过滤器,该过滤器可以解析它并将其转换为通常的请求参数,以便 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>

另请参阅:

  • JSF 2.0 文件上传

相关内容

  • 没有找到相关文章