【问题标题】:JSF 2 : tag wrapper to encapsulate common attribute values?JSF 2:封装公共属性值的标签包装器?
【发布时间】:2011-05-28 04:09:08
【问题描述】:

基于上一个问题How to get ID of calling component in the getter method?,我想请教您的另一个想法:

jsf 页面中有很多重复的代码,例如这些跨组件的示例(注意重复大小和 maxlength 属性):

<h:inputText label="#{msgs.userId}" id="UserId" value="#{userBean.userId}" 
   required="true" 
   size="#{variableConfigBean.getSize(component.id)}" 
   maxlength="#{variableConfigBean.getMaxLength(component.id)}"
/>
<h:inputSecret label="#{msgs.password}" id="Password" value="#{userBean.password}" 
   required="true"  
   size="#{variableConfigBean.getSize(component.id)}" 
   maxlength="#{variableConfigBean.getMaxLength(component.id)}"
/>

我在想:

  1. 为此使用复合组件 输入文本标签,
  2. 在该复合组件的实现部分中硬编码大小和最大长度,
  3. 这样我就不必复制所有 每次我需要使用这些东西 该组件。
  4. 但我必须打开 将界面中的所有属性 该复合组件的部分

这个想法可以吗,或者有其他更好的方法来解决这个问题?

【问题讨论】:

    标签: java jsf-2 facelets


    【解决方案1】:

    你可以这样做。我也在一些项目中实现了它。它只会增加一些(次要)开销。对于这个特定目的,您也可以只使用 Facelets 标记文件而不是 JSF 复合组件。那时定义属性不是强制性的。在您的特定情况下,如果您将 bean 属性名称重用为消息包标签的 id 和键,则可以重构几乎所有重复项。

    例如

    <my:input type="text" bean="#{userBean}" property="userId" required="true" />
    <my:input type="secret" bean="#{userBean}" property="password" required="true" />
    

    在 Facelets 标记文件中包含以下内容:

    <c:set var="id" value="#{not empty id ? id : property}" />
    <c:set var="required" value="#{not empty required and required}" />
    
    <c:choose>
        <c:when test="#{type == 'text'}">
            <h:inputText id="#{id}" 
                label="#{msgs[property]}"
                value="#{bean[property]}" 
                size="#{config.size(id)}" 
                maxlength="#{config.maxlength(id)}" 
                required="#{required}" />
        </c:when>
        <c:when test="#{type == 'secret'}">
            <h:inputSecret id="#{id}" 
                label="#{msgs[property]}"
                value="#{bean[property]}" 
                size="#{config.size(id)}" 
                maxlength="#{config.maxlength(id)}" 
                required="#{required}" />
        </c:when>
        <c:otherwise>
            <h:outputText value="Unknown input type: #{type}" />
        </c:otherwise>            
    </c:choose>
    

    然而,我之前使用&lt;h:outputLabel&gt; 和之后使用&lt;h:message&gt; 实现了它,这使得这样的重构更加合理。

    【讨论】:

    • 然而,我之前使用 和之后使用 实现了它,这使得这样的重构更加合理。
    • &lt;h:outputLabel for="#{id}" value="#{msgs[property]}"/&gt;&lt;c:choose&gt; 之前和&lt;h:message for="#{id}"/&gt; 之后。至于侦听器/验证器,我不确定,但听起来您只需要标签正文中的&lt;ui:insert/&gt;。不过,顺便说一下,我并不反对使用复合组件。根据我的经验,在我的特殊情况下,它们的缺点是它们最终成为单个组件。我的意图是拥有一个包含所有字段的 3 列 &lt;h:panelGrid&gt;,它只适用于标签文件,因为它实际上返回了 3 个组件(标签、输入、消息),而不仅仅是一个。
    • 哦,我明白了,您在考虑返回 3 个组件的复合组件。不错 :) 好的,我现在尝试您的建议。祝我好运。再次感谢..
    猜你喜欢
    • 2017-11-23
    • 1970-01-01
    • 2011-02-23
    • 1970-01-01
    • 2012-11-27
    • 2021-02-27
    • 2019-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多