2012-07-23 31 views
0

據我所知,FacesContext僅在請求範圍內纔可用。我創建了一個嘗試接收FacesContext實例的線程,但它返回null。JSF接收FacesContext外部請求

我的意思是每10秒更新一些應用程序範圍的bean。

線程的run方法:

@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的頭(我已經跳過getter/setter方法):

@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的引用嗎?

+0

您使用ejbs嗎? – 2012-07-23 14:29:16

+0

我不知道它是什麼。 – 2012-07-23 14:57:13

回答

1

由於現在有方法可以在Servlet環境之外訪問/構造FacesContext,我建議您將應用程序作用域對象傳遞給工作線程(執行批處理作業的線程)的構造函數。更新線程中的引用將導致更新應用程序作用域引用,因爲它們都指向同一個實例。

如果你有一個EJB3環境,你可以使用EJB timer + @Singleton bean,而不需要處理線程和範圍。