2011-10-16 33 views
0

在我的申請,我有我使用JSP時以下常量類JSF 2.0:我怎麼能動態生成輸入組件

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

早些時候,我設法動態地呈現輸入字段在此基礎上的文件上傳常量如下:

<% 
    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; 
    ... 
} 

然而,由於這些領域目前動態生成的,我不知道我需要多少屬性來定義提前捕獲這些上傳的文件。

如果有人能給我一個關於如何解決這個問題的建議,我將不勝感激。

最好的問候,

詹姆斯陳

回答

2

把那些性質在另一個JavaBean類,並將這些JavaBeans集合在你的託管bean。

E.g.

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。

+0

非常感謝您的幫助!我從來不知道「ui:repeat」標籤。你對戰斧是對的。其實,我遵循你的[迷你教程](http://stackoverflow.com/questions/5418292/jsf-2-0-file-upload/5424229#5424229)來實現這個文件上傳功能。 =) –