Java 带有 FacesContext.getCurrentInstance().addMessage 的自定义消息未显示在页面中 (JSF)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2341154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 06:21:01  来源:igfitidea点击:

Custom message with FacesContext.getCurrentInstance().addMessage is not displayed in page (JSF)

javajsfjakarta-ee

提问by bblanco

My page:

我的页面:

...
    <div id="header">
       <!-- content header -->
     </div>
     <div id="content">
       <h:messages />
       <h:ouputText value="#{example.text}" />
     </div>
...

My managedBean:

我的托管Bean:

public class ExampleManagedBean(){
       private String text;


       public String getText(){
           FacesContext.getCurrentInstance().
                   addMessage(null, 
                      new FacesMessage(FacesMessage.SEVERITY_WARN, 
                                       "Warning message...", null));
           return text;
       }

       public void setText(String text){
           this.text = text;
       }
   }

My problem is that the warning message not is rendered in page. Why?

我的问题是警告消息未在页面中呈现。为什么?

回答by Piotr Kochański

FacesMessage is send to <h:messages/> during validation phase of JSF lifecycle. In your case getter is used to derive bean property value and no validation is going on, so the message is empty.

FacesMessage 在 JSF 生命周期的验证阶段发送到 <h:messages/>。在您的情况下,getter 用于派生 bean 属性值,并且没有进行验证,因此消息为空。

In theory you can use setter validation, but this is a well known antipattern.

理论上你可以使用 setter 验证,但这是一个众所周知的反模式

You can do "by hand" validation, but in a different way

您可以进行“手动”验证,但方式不同

 <div id="content">
    <h:messages />
    <h:form>
        <h:outputText value="#{example.text}" />
        <h:commandButton value="Click" action="#{example.action}"/>
    </h:form>
 </div>

and the action method is

和动作方法是

public String action(){
   FacesContext.getCurrentInstance().
        addMessage(null,
            new FacesMessage(FacesMessage.SEVERITY_WARN,
                                       "Warning message...", null));
           return null;
}

Much cleaner approach would use built-in or custom validator.

更简洁的方法是使用内置或自定义验证器。

回答by lexicore

I have two ideas.

我有两个想法。

First, the message is added in the getText() getter. If h:messages is rendered before h:outputText, then the message might not be there yet when h:messages is rendered.

首先,将消息添加到 getText() 获取器中。如果 h:messages 在 h:outputText 之前呈现,那么当 h:messages 呈现时消息可能还不存在。

Second, messages disappear on redirects.

其次,消息在重定向时消失。