且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-24 13:18:57

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

You need to provide the so called client id, which you'll find on UIComponent.

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

The following is a quick example of how to use this.

考虑以下 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:

being used on the following 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 消息.

This will add a Faces message with content "Test msg" for the outputText component used in the example.