Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
843 views
in Technique[技术] by (71.8m points)

jsf 2 - How to add a message to a specific component from JSF backing bean

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

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

I want to send a message to it from java, in a manner like:

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

which is sent to h:messages, but to a specific id in a specific form. How can I do this? (Without implementing validation bean or validation method - meaning without throwing validation exception).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...