2012-07-24 51 views
1

此問題與我最近發佈的另一個相關:Understanding HttpServletRequest and cookies in JSFWebFilter,EL和SessionScoped ManagedBean處理記住我登錄

爲了實施記住我登錄JSF,我正在使用cookie並在WebFilter中讀取它。過濾器獲取cookie並在SessionScopedManagedBean中設置cookie值,但由於某些原因,ManagedBean無法在網頁中顯示。

過濾器的的doFilter實現:

@Override 
public void doFilter(ServletRequest request, ServletResponse response, 
     FilterChain chain) 
     throws IOException, ServletException { 

    HttpServletRequest req = (HttpServletRequest) request; 
    Cookie[] cookies = req.getCookies(); 
    if (cookies != null) { 
     for (Cookie cookie : cookies) { 
      if (cookie.getName().equals("MyTestCookie")) { 
       System.out.println("Filter got cookie: " + cookie.getValue()); 
       cookieBean.setValue(cookie.getValue()); 
      } 
     } 
    } 
    chain.doFilter(request, response); 
} 

CookieBean類:

@ManagedBean 
@SessionScoped 
public class CookieBean implements Serializable { 

    private String value; 

    @PostConstruct 
    public void init() { 
     System.out.println("Instantiated CookieBean"); 
    } 

    public String getValue() { 
     System.out.println("CookieBean returning Value: " + value); 
     return value; 
    } 

    public void setValue(String value) { 
     System.out.println("CookieBean getting Value: " + value); 
     this.value = value; 
    } 

    public void create() { 
     ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext(); 
     Map<String, Object> props = new HashMap<String, Object>(); 
     props.put("maxAge", 10000); 
     ec.addResponseCookie("MyTestCookie", "Hello Cookie", props); 
    }  
} 

CookieBeancookieBeanjavax.inject.Inject註釋的方式注入到過濾器。

機構

的index.xhtml

<h:form> 
    <h:commandButton value="Create Cookie!" action="#{cookieBean.create()}" > 
     <f:ajax render="@form" /> 
    </h:commandButton> 
    <p></p> 
    <h:outputText value="Cookie value: #{cookieBean.value}" /> 
</h:form> 

的第一個問題是,設置cookie後,如果我開始一個新的會話(通過打開一個新的瀏覽器會話),網頁ISN」 t知道cookie值,因爲在之後SessionScopedManagedBean被更新頁面顯示。

問題1:如何檢測cookie值及時更新網頁中的rendered屬性?

的第二個問題是,如果我在瀏覽器中按重載(或刷新)按鈕重新加載網頁時,ManagedBean實例是像以前一樣(的@PostConstruct方法是不啓動),但網絡頁面顯示了一個空的cookie值和相同的顯示在服務器的輸出:

CookieBean returning Value: null 
Filter got cookie: Hello Cookie 
CookieBean getting Value: Hello Cookie 

問題2:怎麼可能,一個SessionScopedManagedBean失去其財產不會被重新創建?

回答

0

對問題1的回答:正如在question的接受答案中所解釋的,我只需在後臺bean中進行重定向。 ,這就迫使JSF生產具有在Cookie中一個新的GET請求假設請求的網頁是我的歡迎頁面,我在我的cookieBean寫這篇文章:

FacesContext.getCurrentInstance().getExternalContext().redirect("faces/index.xhtml"); 

好了,這工作得很好,但完整的URL現在顯示在地址欄中。如果有避免這種情況的方法,我會進一步調查。

回答問題2:在SessionScopedcookieBean得到有效實例化兩次,一次部署期間,並通過一個過濾器。問題是我正在使用JSF ManagedBean並注入javax.inject.Inject註解。我通過javax.inject.Namedjavax.enterprise.context.SessionScoped註釋將其製作爲CDI Bean,並且注入現在運行良好。