繁体   English   中英

JSF 2.0:如何动态生成Input组件

[英]JSF 2.0: how can I dynamically generate Input component

在我的应用程序中,我有以下Constants类

public class Constants {
    ...
    public static final int MAX_NUM_OF_PICTURES = 2
    ...
}

早在我使用JSP时,我设法根据此常量动态呈现用于上载文件的输入字段,如下所示:

<%
    for (int i = 1; i < Constants.MAX_NUM_OF_PICTURES + 1; i++) {
%>
<tr>
    <td>Upload Picture <%= i %></td>
    <td><input name="<%= i%>" type="file" /></td>
</tr>
<tr>
    <td>Description <%= i %></td>
    <td><input type="text" name="<%= "description" + i%>" id="description" /></td>
</tr>
<%
    }
%>

目前,我正在尝试使用JSF来完成上述任务。 如果这些输入字段不是动态生成的,我可以在我的支持bean中轻松定义以下属性:

@ManagedBean
@RequestScoped
public class MrBean {
   ...
   private UploadedFile picture1;
   private String       pictDescription1;
   ...
}

但是,由于这些字段现在是动态生成的,我不知道需要提前定义多少属性才能捕获这些上传的文件。

如果有人能就我应该如何解决这个问题给我一个建议,我将非常感激?

最好的祝福,

詹姆斯特兰

将这些属性放在另一个javabean类中,并在托管bean中包含这些javabeans的集合。

例如

public class Picture {

    private UploadedFile file;
    private String description;

    // ...
}

@ManagedBean
@ViewScoped
public class Profile {

    List<Picture> pictures;

    public Profile() {
        pictures = new ArrayList<Picture>();

        for (int i = 0; i < Constants.MAX_NUM_OF_PICTURES; i++) {
            pictures.add(new Picture());
        }
    }

    // ...
}

然后你可以在例如<ui:repeat> (或者可能是<h:dataTable>循环它,但如果你想要两个重复的行而不是一个,那么这不太合适。

<table>
    <ui:repeat value="#{profile.pictures}" var="picture" varStatus="loop">
        <tr>
            <td>Upload Picture #{loop.index + 1}</td>
            <td><t:inputFileUpload value="#{picture.file}" /></td>
        </tr>
        <tr>
            <td>Description #{loop.index + 1}</td>
            <td><h:inputText value="#{picture.description}" /></td>
        </tr>
    </ui:repeat>
</table>

我不知道你用什么组件库来上传文件,所以我认为它只是Tomahawk。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM