【问题标题】:What is the recommended way to avoid repeated code in ManagedBeans?避免在 ManagedBeans 中重复代码的推荐方法是什么?
【发布时间】:2015-11-09 20:56:43
【问题描述】:

至于良好的用户反馈,我在我的 web 应用程序的多个站点上使用消息。

要添加消息,我简单地使用:

FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(type, "", message));

我为typemessage 添加了变量,因为它取决于不同的验证。

嗯,我为不同的站点使用不同的ManagedBeans,这很正常。

我想到了在不同的ManagedBeans 中添加这些消息的最佳做法是什么。

目前,我总是使用上面的代码 sn-p 超过 30 次(肯定会越来越多)。

我应该使用SessionScopedannotated 还是@ApplicationScoped 创建一个Bean?你有什么其他的提示吗,我应该知道吗?

【问题讨论】:

    标签: jsf jakarta-ee jsf-2


    【解决方案1】:

    只需将重复的静态代码隐藏到可重用的 static 方法中,使其更加 DRY(“不要重复自己”)。

    以这样的方式设计静态方法,以便您最终可以从中重构,

    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(type, "", message));
    

    这样的事情,

    Messages.addGlobalInfo(message);
    

    甚至使用import static com.example.Messages.*;(Eclipse:Ctrl+Shift+M 行):

    addGlobalInfo(message);
    

    它不需要是托管 bean,因为它不保存任何状态。此外,您应该使此类实用程序类的默认构造函数为private,因此Java/JSF 首先可以不通过new 运算符或Class#newInstance() 在反射中构造它。如果您正在使用 CDI,请在必要时使用 @Typed 使用空值对其进行注释,以防止它通过 Bean<T> 注册为托管 bean 候选。

    @Typed
    public final class Messages {
    
        private Messages() {}
    
        // ...
    }
    

    JSF 实用程序库OmniFaces 正好有这个实用程序类:org.omnifaces.util.Messages

    【讨论】:

    • 嗯,谢谢你指点这个类(自己写的)。我用Messages#addGlobal(Severity,String)。我想,如果你已经使用了 OmniFaces,它会比其他方式干净得多。
    • 不客气。事实上,几乎所有重复的 JSF 代码最终都会出现在 OmniFaces 中。
    【解决方案2】:

    可能只是将此代码移动到某个实用程序类:

    public void static addMessage(FacesMessage.Severity type, String message){
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(type, "", message));
    }
    

    您还可以使用一个参数创建多个方法:addInfoMessage、addErrorMessage、...

    【讨论】:

    • 我应该如何注释这个实用程序类?
    猜你喜欢
    • 2016-01-18
    • 2022-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-01
    • 2013-03-29
    相关资源
    最近更新 更多