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