如何从<ui:repeat> </ui:repeat>中的jsf页面获取Backing Bean的参数

时间:2013-04-04 21:20:04

标签: jsf-2 primefaces

我的xhtml:

<ui:repeat value="#{c.voices}" var="v"> 
    <h:form enctype="multipart/form-data">  
        <p:fileUpload fileUploadListener="#{AddNote.handleFileUpload}"
            converterMessage="converterMessage"
            mode="advanced"  
            update="messages"  
            sizeLimit="100000"                                                 
            allowTypes="/(\.|\/)(gif|jpe?g|png)$/">
        </p:fileUpload>  
        <p:growl id="messages" showDetail="true"/>                                     
    </h:form> 
</ui:repeat>

我的BackingBean:

 public void handleFileUpload(FileUploadEvent event) {
    //int v.id= here i need to know the v.id value from ui:repeater
    FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
    FacesContext.getCurrentInstance().addMessage(null, msg);
}

c.voices 是对象列表。每个对象都有 id 属性。我需要知道 handelFileUpload 中的 id ,我该如何实现?

1 个答案:

答案 0 :(得分:3)

我只是将v.id放在隐藏的字段中:

你的xhtml:

<ui:repeat value="#{c.voices}" var="v">
    <h:form enctype="multipart/form-data">
        <input type="hidden" name="vid" value="#{v.id}" />
        <p:fileUpload fileUploadListener="#{AddNote.handleFileUpload}"
            converterMessage="converterMessage"
            mode="advanced"
            update="messages"
            sizeLimit="100000"
            allowTypes="/(\.|\/)(gif|jpe?g|png)$/">
        </p:fileUpload>
        <p:growl id="messages" showDetail="true"/>
    </h:form> 
</ui:repeat>

然后使用FacesContext

将其恢复到bean中

你的BackingBean:

public void handleFileUpload(FileUploadEvent event) {
    HttpServletRequest request = (HttpServletRequest) 
        FacesContext.getCurrentInstance().getExternalContext().getRequest();
    request.getParameter("vid"); // <= Here you are!
}

<强>更新

正如评论中所述,每次迭代都会拥有自己的<h:form,并拥有自己的<input type="hidden" name="vid"。上传文件时,handleFileUpload将使用附上表单的数据触发,因此vid参数将与正确的#{v.id}

一起发送

更新2

正如BalusC评论的那样,你最好以这种方式得到vid参数:

public void handleFileUpload(FileUploadEvent event) {
     FacesContext.getCurrentInstance().getExternalContext()
        .getRequestParameterMap().get("vid") // <= Here you are!
}