【问题标题】:Passing and using parameters between JSF includesJSF之间传递和使用参数包括
【发布时间】:2018-06-07 19:50:25
【问题描述】:

我一直在尝试理解 JSF 模板和 include 属性以及在组件之间传递参数。在 Anghel Leonard 的 Mastering JavaServer Faces 2.2 中,我遇到了以下传递参数的示例,但我并不完全理解。

鉴于此 bean:

@Named
@ViewScoped
public class TemplatesBean implements Serializable {

    private String msgTopDefault="";
    private String msgBottomDefault="";
    private String msgCenterDefault="No center content ... press the below button!";

    public void centerAction(){
        this.msgCenterDefault="This is default content";
    }

    // Getters and setters
}

参数被传递给contentDefault.xhtml

<ui:insert name="content">
  <ui:include src="/template/default/contentDefault.xhtml">
    <ui:param name="templatesBeanName" value="#{templatesBean}"/>
    <ui:param name="contentPropertyName" value="msgCenterDefault"/>
  </ui:include>
</ui:insert>

那么,在contentDefault.xhtml内,参数使用如下:

<ui:composition>            
     <h:outputText value="#{templatesBeanName[contentPropertyName]}"/>
     <h:form>
         <h:commandButton value="Center Button" action="#{templatesBeanName['centerAction']()}"/>               
     </h:form>
</ui:composition>

我以前从未使用过方括号语法,但是如果传入了对templatesBean 的引用,为什么不直接使用它来访问属性或调用操作方法呢?例如,以下代码也适用于我,而且看起来更简单:

<h:form>
     <h:commandButton value="Center Button" action="#{templatesBeanName.centerAction()}"/>
</h:form>

认识到书中的例子可能是一个人为的例子来说明一个观点,是否存在适合其他语法的用例?

【问题讨论】:

    标签: jsf-2 el


    【解决方案1】:

    我不知道或拥有这本书,所以我无法调查他们想要说明的内容,但我可以通过查看您发布的完整示例来推断这一点,而不仅仅是关于centerAction 的部分。

    如果你看

    <ui:insert name="content">
      <ui:include src="/template/default/contentDefault.xhtml">
        <ui:param name="templatesBeanName" value="#{templatesBean}"/>
        <ui:param name="contentPropertyName" value="msgCenterDefault"/>
      </ui:include>
    </ui:insert>
    

    您会看到 2 个参数被传递,templatesBeanNamecontentPropertyName

    <ui:composition>            
         <h:outputText value="#{templatesBeanName[contentPropertyName]}"/>
         <h:form>
             <h:commandButton value="Center Button" action="#{templatesBeanName['centerAction']()}"/>               
         </h:form>
    </ui:composition>
    

    您刚刚指向带有action="#{templatesBeanName['centerAction']()}" 的行,这是一个在suqare 括号中具有静态值的动态bean,通过添加() 作为后缀制成方法,您将在其上方看到另一行代码

    <h:outputText value="#{templatesBeanName[contentPropertyName]}"/>
    

    这里有效的做法是使用动态 beanAND 动态属性名称。

    所以我的结论是,通过这个示例,他们试图说明的是您能够传递动态 bean,并且在该 bean 上使用静态或动态方法和属性(静态属性和动态方法不是在示例中)

    【讨论】:

    • 传递动态bean动态属性——通过参数传递行为听起来几乎像lambda。
    • @craigcaulfield:是的!让我们再次开始在视图中编程;-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-21
    • 2012-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多