至于良好的用户反馈,我在我的webapplication中使用多个站点上的消息.
要添加消息,我只需使用:
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(type, "", message));
Run Code Online (Sandbox Code Playgroud)
我为type
和添加了变量message
,因为它取决于不同的验证.
好吧,我使用不同ManagedBeans
的网站,这是正常的.
我想到了,在不同的地方添加这些消息的最佳做法是什么ManagedBeans
.
目前,我总是使用上面的代码片段超过30次(并且它将变得越来越肯定).
我应该创建带SessionScoped
注释的Bean 还是@ApplicationScoped
?你有其他任何提示吗,我应该知道吗?
只需将重复的静态代码隐藏到可重用的static
方法中,使其更加干燥("不要重复自己").
以这样的方式设计静态方法,你最终可以从中重构,
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(type, "", message));
Run Code Online (Sandbox Code Playgroud)
对这样的事情,
Messages.addGlobalInfo(message);
Run Code Online (Sandbox Code Playgroud)
或者甚至用import static com.example.Messages.*;
(Eclipse:Ctrl+ Shift+ M行):
addGlobalInfo(message);
Run Code Online (Sandbox Code Playgroud)
它不需要是托管bean,因为它不包含任何状态.此外,您应该创建这样的实用程序类的默认构造函数private
,因此Java/JSF首先不能通过new
运算符或Class#newInstance()
反射构造它.如果您正在使用CDI,请在必要时@Typed
使用空值进行注释,以防止它被注册为托管bean候选者Bean<T>
.
@Typed
public final class Messages {
private Messages() {}
// ...
}
Run Code Online (Sandbox Code Playgroud)
JSF实用程序库OmniFaces正是这个实用程序类:org.omnifaces.util.Messages
.
归档时间: |
|
查看次数: |
111 次 |
最近记录: |