如何从JSF支持bean向特定组件添加消息

Ben*_*hik 17 jsf richfaces jsf-2

我有一个h:inputText和一个连接到它的h:消息:

<h:inputText id="myText" value="#{myController.myText}" />
<a4j:outputPanel>
    <h:message for="myText" .../>
</a4j:outputPanel>
Run Code Online (Sandbox Code Playgroud)

我想从java发送消息,方式如下:

FacesContext.getCurrentInstance().addMessage(arg0, arg1);
Run Code Online (Sandbox Code Playgroud)

发送到h:消息,但发送到特定表单中的特定ID.我怎样才能做到这一点?(没有实现验证bean或验证方法 - 意味着没有抛出验证异常).

Arj*_*jms 32

你需要提供所谓的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 "";
    }

}
Run Code Online (Sandbox Code Playgroud)

用于以下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>
Run Code Online (Sandbox Code Playgroud)

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

  • 给定组件的(相对)id,您无法普遍计算clientId.JSF规范只要求那些ID在命名容器的范围内是唯一的.如果您认为这些相对ID在您的应用程序中足够独特,您可以使用findComponent从视图根开始定位组件,例如``context.getViewRoot().findComponent("myText")`` (6认同)
  • 是的,您可以从发送到浏览器的标记中获取此 ID。但是依赖于它是相当脆弱的,因为当您移动组件或将其他组件添加到视图时,此 ID 可能会更改。 (2认同)

小智 7

另一种方法是:给表单提供一个ID,比如"form1",然后,当添加消息时,clientId是"form1:test".