1
我正在用primefaces 5.0開發jsf,如果在後臺bean中滿足條件,我需要將用戶重定向到另一個頁面。所以我使用p:poll
讓頁面每秒檢查一次條件,如果條件滿足,將用戶重定向到另一頁面。如何使用primefaces輪詢重定向?
我創建了一個小項目來試試這個場景,它使用poll來檢查int cnt
是否> = 10,如果是的話,將用戶重定向到welcomePrimefaces.xhtml
。此外,還有另一個線程T1
,用於簡單地增加cnt
,以便條件可能滿足一段時間。
這裏是我做了什麼:
頁:(沒什麼特別的,只是輪詢每秒檢查狀態)
<h:form>
Hello from Facelets
<br />
<p:poll interval="1" listener="#{mainBean.checkStatus()}"/>
</h:form>
輔助Bean:
public class MainBean {
private Integer cnt = 0;
@PostConstruct
public void init() {
Thread t1 = new Thread(new T1(), "test");
t1.start();
}
public void checkStatus() {
synchronized (cnt) {
System.out.println("cnt:" + cnt);
if (cnt >= 10) {
try {
Object request = FacesContext.getCurrentInstance().getExternalContext().getRequest();
Object response = FacesContext.getCurrentInstance().getExternalContext().getResponse();
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.sendRedirect(httpRequest.getContextPath()
+ "/welcomePrimefaces.xhtml");
} catch (IOException ex) {
System.out.println("Error!");
}
}
}
}
private class T1 implements Runnable {
@Override
public void run() {
try {
while (true) {
Thread.sleep(1000);
synchronized (cnt) {
cnt++;
}
}
} catch (InterruptedException ex) {
System.out.println("Thread Error!");
}
}
}
}
的結果是cnt
被打印了10次(從0到9),並且在此之後,它被存儲,甚至沒有執行輪詢。
那麼我的代碼有什麼問題?請幫幫我。
在此先感謝。
「不要過分複雜化自己」,這是你做了什麼,我相信。 –
@SujanSivagurunathan,答案是第一個代碼段。第二個代碼片段屬於Mojarra實現,我附加它只是爲了說明它在ajax和非ajax請求之間的差異。 –
那麼這是最短的答案。對不起,我認爲重定向方法是你自己的實現。 –