2013-05-30 34 views
9

我有一個Facelet可能在不同的應用程序中使用。 我不想複製它,但重複使用它。我需要傳遞將管理視圖作爲參數的後臺bean,因爲某些邏輯可能會因使用它的應用程序而有所不同。將backing bean作爲參數傳遞給Facelet包括

我不想使用複合組件,只是包含Facelet並指定哪個bean將管理該視圖。我怎樣才能做到這一點?

讓我舉一個例子:

<ui:composition template="/resources/common/templates/template.xhtml" 
    xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" 
    xmlns:f="http://java.sun.com/jsf/core" xmlns:ui="http://java.sun.com/jsf/facelets" 
    xmlns:c="http://java.sun.com/jsp/jstl/core" xmlns:a4j="http://richfaces.org/a4j" 
    xmlns:rich="http://richfaces.org/rich" xmlns:fn="http://java.sun.com/jsp/jstl/functions"> 
    <ui:define name="content"> 
     <!-- somehow establish the backing bean that will manage formView.xhtml --> 
     <!-- f:set assign="ParameterBean" value="#{Bean}"/--> 
     <ui:include src="formView.xhtml" /> 
    </ui:define> 
</ui:composition> 

formView.xhtml:

<ui:composition template="/resources/common/templates/template.xhtml" 
    xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" 
    xmlns:f="http://java.sun.com/jsf/core" xmlns:ui="http://java.sun.com/jsf/facelets" 
    xmlns:c="http://java.sun.com/jsp/jstl/core" xmlns:a4j="http://richfaces.org/a4j" 
    xmlns:rich="http://richfaces.org/rich" xmlns:fn="http://java.sun.com/jsp/jstl/functions"> 
    <ui:define name="content"> 
     <h:outputText value="#{ParameterBean.texto}" /> 
    </ui:define> 
</ui:composition> 

回答

22

您可以使用<ui:param>了點。它需要嵌套在<ui:include>中。

<ui:include src="formView.xhtml"> 
    <ui:param name="ParameterBean" value="#{Bean}" /> 
</ui:include> 

無關的具體問題,標準Java Naming Conventions狀態實例變量名稱必須以小寫字母開頭。您應該以分別使用parameterBean#{bean}的方式更改您的代碼。

+0

你怎麼引用'ParameterBean'來調用實例方法? – Thufir

0

因爲我發現它有用昨天,當我一直在尋找這一點,這裏是如何做到這一點,沒有外來模板一個簡單的版本,定義和命名空間:

File1.xhtml(根標籤並不重要)

<ui:include src="File2.xhtml"> 
    <ui:param name="person" value="#{whatever_value_you_want_to_pass}" /> 
</ui:include> 

File2.xhtml

<ui:composition ... xmlns:h="http://java.sun.com/jsf/html" 
    xmlns:ui="http://java.sun.com/jsf/facelets" ... > 
    <h:outputLabel value="#{person.name}" /> 
</ui:composition> 


您也可以嵌套在進一步同樣的方式。

File1.xhtml

<ui:include src="File2.xhtml"> 
    <ui:param name="person" value="#{whatever_value_you_want_to_pass}" /> 
</ui:include> 

File2.xhtml

<ui:composition ... xmlns:ui="http://java.sun.com/jsf/facelets" ... > 
    <ui:include src="File3.xhtml"> 
    <ui:param name="name" value="#{person.name}" /> 
    </ui:include> 
</ui:composition> 

File3.xhtml

<ui:composition ... xmlns:h="http://java.sun.com/jsf/html" 
    xmlns:ui="http://java.sun.com/jsf/facelets" ... > 
    <h:outputLabel value="#{name.length}" /> 
</ui:composition> 
+0

我不明白這與以下答案有何不同? – Kukeltje

+0

我很難理解答案應該如何使用,所以我試圖讓其他人更加明顯。 – Chris

+0

然後,您可以「編輯」問題並刪除這些內容,並在「評論」中提及您爲什麼這麼做。當別人「接受」這個變化時,它就會顯現出來。那麼不需要再創建第二個答案。 – Kukeltje