How to add a message to a specific component from JSF backing bean

后端 未结 2 1068
盖世英雄少女心
盖世英雄少女心 2020-12-28 16:44

I have an h:inputText and an h:message connected to it:



    <         


        
相关标签:
2条回答
  • 2020-12-28 17:28

    Another way to do that is: give an ID to the form, like "form1", then, when add the message, the clientId is "form1:test".

    0 讨论(0)
  • 2020-12-28 17:29

    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.

    Consider the following 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 "";
        }
    
    }
    

    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>
    

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

    0 讨论(0)
提交回复
热议问题