JSF接收FacesContext外部请求



据我所知,FacesContext仅在请求范围内可用。我创建了一个线程,试图接收FacesContext的实例,但它返回null。

我的观点是每10秒更新一些应用程序范围的bean。

线程的运行方法:

@Override
public void run()
{
    while (true)
    {
        try
        {
            TimeView timeView = (TimeView)FacesContext.getCurrentInstance().
                    getExternalContext().getApplicationMap().get("timeView"); 
            // FacesContext.getCurrentInstalce() returns null
            timeView.update();
            Thread.sleep(10000);
        }
        catch (InterruptedException ex)
        {
            System.out.println(ex);
        }
    }
}

TimeView的标题(我跳过了getters/ssetters):

@ManagedBean(eager=true, name="timeView")
@ApplicationScoped
public class TimeView implements Serializable
{
    private int hour;
    private int minutes;
    private int seconds;
    public TimeView()
    {
        update();
    }
    public void update()
    {
        Date date = new Date();
        setHour(date.getHours());
        setMinutes(date.getMinutes());
        setSeconds(date.getSeconds());
    }

faces-config.xml:

<?xml version="1.0" encoding="UTF-8"?>
<faces-config
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
    version="2.0">
    <managed-bean>
        <managed-bean-name>timeView</managed-bean-name>
        <managed-bean-class>foogame.viewBeans.TimeView</managed-bean-class>
        <managed-bean-scope>application</managed-bean-scope>
    </managed-bean>
</faces-config>

那么,有没有一种方法可以在这个线程中接收对我的应用程序范围的bean的引用?

由于现在有办法在Servlet环境之外访问/构造FacesContext,我建议您将应用程序范围的对象传递给工作线程(执行批处理作业的线程)的构造函数。更新线程中的引用将导致更新应用程序范围的引用,因为它们都指向同一个实例。

如果您有一个EJB3环境,您可以使用EJB定时器+@Singletonbean,而不需要处理线程和作用域。

最新更新