2013-02-03 24 views
1

我想在JSF2.0中關閉窗口期間使會話無效。所以我寫了下面的代碼來做到這一點:使JSF2.0無效會話Mojarra和JQuery

var preventUnloadPrompt; 
var messageBeforeUnload = "my message here - Are you sure you want to leave this page?"; 
$('a').live('click', function() { 
    preventUnloadPrompt = true; 
}); 
$('form').live('submit', function() { 
    preventUnloadPrompt = true; 
}); 
$(window).bind("beforeunload", function(e) { 
    var rval; 
    if (preventUnloadPrompt) { 
     return; 
    } else { 
     // return messageBeforeUnload; 
     doInvalidate(); 
    } 
    return rval; 
}); 

function doInvalidate() 
{ 
    $.ajax({ 
     url: "http://localhost:8080/MyPrj/SessionTimeout", 
     type: 'GET' 
    }); 
} 

而我的servlet如下:

public class SessionTimeout extends HttpServlet { 
    ..... 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
     System.err.println("IN SESSION TIMEOUT GET!!!"); 
      FacesContext.getCurrentInstance().getExternalContext().invalidateSession(); 
    } 
    ..... 
} 

推出我的第一頁JSF2.0(這時候FacesContext中,肯定有我初始化)後,我試圖關閉窗戶。我可以看到我的SessionTimeout servlet正在調用,但FacesContext.getCurrentInstance().getExternalContext().invalidateSession();正在拋出NullPointerException。爲什麼會發生?在我的servlet的AJAX調用期間,我看不到FacesContext?如果以上是不可能的,可以建議其他方法嗎?

回答

3

FacesContextFacesServlet創建,因此僅當請求由FacesServlet提供時纔可用。換句話說,它只能在JSF構件中使用,如託管的bean,階段監聽器等,但絕對不是在獨立於JSF調用的「普通香草」servlet中。

只需使用標準的servlet API的方法,如爲JSF使用的「幕後」(你知道,JSF是一個Servlet的MVC框架,心裏很不FacesServlet servlet的!)。要使會話失效,只需要exactly the same,因爲ExternalContext#invalidateSession()正在執行。

request.getSession().invalidate(); 
+0

是的。感謝您的回答。 – MyFist

+0

謝謝。它工作正常。 – MyFist

+0

不客氣。 – BalusC