从支持 Bean 刷新 JSF/PrimeFaces 接口

Refreshing a JSF/PrimeFaces interface from the backing Bean

我的目标是使用 JSF and/or PrimeFaces 在网页上显示文本。文本由服务器端的进程实时更新。

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:p="http://primefaces.org/ui">

    <h:body>
        <f:view id="view">
            <f:event type="preRenderView" listener="#{MyBean.init}"/>
            <h:form>
                <p:outputLabel id="output" value="#{MyBean.text}"/>
            </h:form>
        </f:view>
    </h:body>
</html>

我的支持 bean 将文本映射到 p:outputLabel。我还向 bean 添加了一个修改文本的方法 foo()。此方法由后台的另一个进程 运行 调用(它持有指向 bean 的指针)。

@ManagedBean(name="MyBean")
@SessionScoped
public class MyBean {
    private String text = "text";
    public void init() {
        MyOtherClass.getPointer(this);
    }
    public String getText() {
        return text;
    }
    public String foo(String s) {
        text = text + s;
        // ...and refresh ?
    }
}

目前我无法做到的是,每次更新文本时自动update/refresh 视图。我能做的最好的就是让用户手动刷新网页,或者使用p:poll定期刷新。

我研究过这个,我发现了非常相似的话题;答案通常是使用 FacesContext.getCurrentInstance() (JSF) 或 RequestContext.getCurrentInstance() (PrimeFaces) 来访问组件并刷新它。我试过了,但是上下文在 foo() 中不可用。

我想这是一个生命周期问题。我对 JSF 的了解非常有限。感谢任何帮助。

当 bean 从非 jsf 后端调用更新时,您无法从 bean 访问 faces 上下文。为此使用 PrimeFaces 推送。