2011-08-23 65 views
0

我正在做一個登錄。問題是:我的isUserLoggedIn()方法被其他會話多次調用(我使用 (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false)進行了檢查)。CDI SessionScoped Bean會產生很多會話

的登錄豆(的JSF頁面)是這樣的:

@Named 
@SessionScoped 
public class Login implements Serializable { 

    @Inject 
    private Credentials credentials; 

    private UserData user; 

    public String login() { 
     if (this.credentials.getUsername().equals("daniel")) { 
      user = new UserData("Daniel"); 
      return "success"; 
     } 
     return "failure"; 
    } 

    public boolean isUserLoggedIn() { 
     return user != null; 
    } 

    public String logout() { 
     user = null; 
     ((HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false)).invalidate(); 
     return "success"; 
    } 

    public String getUsername() { 
     return getUser() == null ? "" : getUser().getUsername(); 
    } 

    @Produces 
    public UserData getUser() { 
     return user; 
    } 
} 

那麼,什麼情況是:當登錄()被調用時,我可以通過的getSession(),它是X見,但隨後,之後在嘗試訪問另一個頁面時,在調用isUserLoggedIn()時,getSession()方法返回Y而不是X,並且user屬性爲null。通常情況下,只需要一次請求就會調用isUserLoggedIn()方法多次,每次調用時都會更改會話。

順便說一句,我使用JBoss AS7決賽,和我的faces-config.xml中如下:

<?xml version="1.0" encoding="UTF-8"?> 
<faces-config version="2.0" xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xi="http://www.w3.org/2001/XInclude" 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"> 

    <navigation-rule> 
     <from-view-id>/login.xhtml</from-view-id> 
     <navigation-case> 
      <from-action>#{login.login}</from-action> 
      <from-outcome>success</from-outcome> 
      <to-view-id>/secured/home.xhtml</to-view-id> 
      <redirect /> 
     </navigation-case> 
     <navigation-case> 
      <from-action>#{login.login}</from-action> 
      <from-outcome>failure</from-outcome> 
      <to-view-id>/login.xhtml</to-view-id> 
      <redirect /> 
     </navigation-case> 
    </navigation-rule> 
    <navigation-rule> 
     <from-view-id>/*.xhtml</from-view-id> 
     <navigation-case> 
      <from-action>#{login.logout}</from-action> 
      <from-outcome>success</from-outcome> 
      <to-view-id>/login.xhtml</to-view-id> 
      <redirect /> 
     </navigation-case> 
    </navigation-rule> 
</faces-config> 

任何想法?謝謝。

+0

這個問題是不是真的可以在你自己的調試工作沒有負責。關鍵是,您的客戶不支持Cookie,或者您正在重新創建每個請求的會話。第一步是使用像Firebug這樣的HTTP流量檢查器來檢查會話cookie。服務器是否會在每個響應中都返回一個新的「Set-Cookie」?或者客戶拒絕在每個請求中返回「Cookie」?這應該有助於打擊罪魁禍首。 – BalusC

+0

感謝您的回答,Balusc。過了一段時間後,我發現問題與URL路徑有關。該Cookie是爲路徑生成的,並且在更改路徑並嘗試訪問會話時,會生成另一個路徑。 – dgimenes

回答

1

經過一段時間後,我發現問題與URL路徑有關。該Cookie是爲路徑生成的,並且在更改路徑並嘗試訪問會話時,會生成另一個路徑。

無論如何,我發現這肯定不是保護Java EE應用程序的方法(請參閱Java EE 6手冊),所以我會採用其他方式。

謝謝。