【问题标题】:How to add a message to a specific component from JSF backing bean如何从 JSF 支持 bean 向特定组件添加消息
【发布时间】:2011-07-14 09:09:30
【问题描述】:

我有一个 h:inputText 和一个 h:message 连接到它:

<h:inputText id="myText" value="#{myController.myText}" />
<a4j:outputPanel>
    <h:message for="myText" .../>
</a4j:outputPanel>

我想从 java 向它发送一条消息,方式如下:

FacesContext.getCurrentInstance().addMessage(arg0, arg1);

发送到 h:messages,但发送到特定形式的特定 id。 我怎样才能做到这一点? (没有实现验证 bean 或验证方法 - 意思是没有抛出验证异常)。

【问题讨论】:

    标签: jsf jsf-2 richfaces


    【解决方案1】:

    您需要提供所谓的client id,您可以在UIComponent 上找到它。

    以下是如何使用它的快速示例。

    考虑以下 bean:

    @ManagedBean
    @RequestScoped
    public class ComponentMsgBean {
    
        private UIComponent component;
    
        public UIComponent getComponent() {
            return component;
        }
    
        public void setComponent(UIComponent component) {
            this.component = component;
        }
    
        public String doAction() {
    
            FacesContext context = FacesContext.getCurrentInstance();
    
            context.addMessage(component.getClientId(), new FacesMessage("Test msg"));
    
            return "";
        }
    
    }
    

    正在以下 Facelet 上使用:

    <html 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" 
        >
    
        <h:body>
    
            <h:form>
                <h:outputText id="test" value="test component" binding="#{componentMsgBean.component}"/>
                <h:message for="test"/>
    
                <h:commandButton value="click me" action="#{componentMsgBean.doAction}" />
            </h:form>
    
        </h:body>
    </html>
    

    这将为示例中使用的 outputText 组件添加内容为“Test msg”的 Faces 消息。

    【讨论】:

    • 那么,没有绑定我只需要知道为组件的 id 生成的 clientId 就可以了?
    • 是的,您可以从发送到浏览器的标记中获取此 ID。但是这取决于这相当脆弱,因为当您移动组件或将其他组件添加到视图时,此 ID 可能会发生变化。
    • 好的,但是我需要不绑定发送消息。从Id中找出clientId的任何简单方法? (没有 TLD 功能)
    • 鉴于组件的(相对)id,您无法普遍计算 clientId。 JSF 规范只要求这些 Id 在命名容器的范围内是唯一的。如果您认为这些相对 ID 在您的应用程序中足够独特,您可以使用 findComponent 从视图根目录开始定位组件,例如context.getViewRoot().findComponent("myText")
    • 谢谢@Arjan,即使过了这么久你仍然在帮助我
    【解决方案2】:

    另一种方法是:给表单一个ID,如“form1”,然后,添加消息时,clientId为“form1:test”。

    【讨论】:

      猜你喜欢
      • 2011-03-24
      • 2018-01-31
      • 2011-05-03
      • 2012-11-15
      • 2012-04-01
      • 2018-05-19
      • 2011-10-15
      • 1970-01-01
      相关资源
      最近更新 更多