java - 不调用jsf中的setter方法

标签 java jsf file-upload jsf-2 myfaces

我正在研究javas服务器界面。我使用 User.java 类作为模型,UserController 作为 Controller ,使用 index.xhtml,ViewProfile,xhtml 作为 View 。我跟踪了以下代码,我观察到 setUploadedFile(UploadedFile file){} 的 setter 方法未调用。而其他两个 setter 正在调用。并且它给出了 NullPointerException。是什么原因 ?我不明白。这是代码

UserController.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>

最佳答案

<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>

另请参阅:

关于java - 不调用jsf中的setter方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14518328/

相关文章:

ios - 上传到s3,iOS成功回调

python - 如何直接从您自己的云端硬盘将 .txt(或其他文件类型)导入 Google Colab 笔记本?

java - 在 Appium Java Android 测试中单击菜单项时页面源未更新

java - 如何获取.jar 中的资源?

java - jdbcAuthentication() 而不是 inMemoryAuthentication() 不提供访问权限 - Spring Security 和 Spring Data JPA

jsf - 如何在 Bootsfaces 数据表列中显示图像

javascript - 在 Firefox 和 IE 中禁用/禁用后退按钮的替代方法

java - 动态加载 Groovy 类并调用管道脚本中的方法

css - 在特定 p 上应用 CSS :dataTable component instead of on all p:dataTable components

asp.net-mvc - dropzonejs 多文件上传无法按预期工作