2013-01-22 40 views
4

我想添加到我的web應用動態麪包屑使用Primefaces組件。我創建了一個模型來將項目推送到麪包屑導航欄,以便當其中一個鏈接被跟蹤時,尾部鏈接被刪除。這在大多數情況下都適用,但有時bradcrumb的行爲並不像我期望的那樣。基本上,爲了跟蹤登錄頁面,我在每個可導航頁面上添加了一個preRenderView偵聽器,並在會話作用域bean中實現了模型更新邏輯。動態麪包屑與primefaces

<f:event type="preRenderView" listener="#{bcb.onRenderView}" /> 
    <f:attribute name="pageName" value="ThisPage" /> 

監聽器接收頁面名稱作爲屬性,並從外部上下文獲取完整的URL(包括查詢字符串)這些信息與來自UIViewRoot創建的唯一ID一起,被用來建立被在模型上推一個BreadCrumbItem:模型的

public void onRenderView(ComponentSystemEvent evt) { 
    UIViewRoot root = (UIViewRoot)evt.getSource(); 
    final String reqUrl = FacesUtils.getFullRequestURL(); 
    String pageName = (String) evt.getComponent().getAttributes().get("pageName"); 
    if(pageName != null) { 
    model.push(new BreadCrumbItem(root.createUniqueId(), pageName, reqUrl)); 
    } else { 
    model.reset(); 
    } 
} 

push()reset()方法是這樣實現的:

/** 
* When a link is pushed on the bread crumb, the existing items are analyzed 
* and if one is found to be equal to the pushed one, the link is not added 
* and all the subsequent links are removed from the list. 
* 
* @param link 
*   the link to be added to the bread crumb 
*/ 
public void push(BreadCrumbItem link) { 
    boolean found = removeTrailing(link); 
    if(!found) { 
     addMenuItem(link); 
    } 
} 

/** 
* Reset the model to its initial state. Only the home link is retained. 
*/ 
public void reset() { 
    BreadCrumbItem home = new BreadCrumbItem(); 
    removeTrailing(home); 
} 

這種方法是否可行?你能否提出一些更好的方法來跟蹤頁面導航,而不需要利用生命週期監聽器?非常感謝你的幫助。

回答

3

我已經爲我的網絡應用程序實現了我自己的一個,在我的情況下我沒有使用p:breadCrumb組件,因爲它使用按鈕實現。

基本上,我有一個包含堆棧(導航堆棧)的@SessionScoped bean,將所有的url存儲在breadcrumb中,併爲它們中的每一個存儲params。該視圖(xhtml)部分由p:button元素組成,其中包含堆棧存儲的url的outcome

當您導航到一個URL,相應的bean的f:event type="preRenderView"被稱爲(結合的方式,你這樣做)和豆從URL的參數,可以認爲它建立自己後入堆棧(而不是豆本身,因爲它的@ViewScoped並將被銷燬,只是網址和參數)。

如果你點擊一個後退按鈕,你會發送一個附加的參數,它表示按鈕的索引。根據該索引,目的地bean知道你正在嘗試恢復這樣的視圖,因此要求導航堆棧查看該視圖params,並且導航堆棧刪除其後的navegable。

我花了一段時間,但它功能齊全。祝你好運。使用session範圍內保存當前導航狀態時

編輯

要小心。它會影響所有打開的選項卡,因此可能不是您想要的,除非您希望最終用戶只在一個選項卡中使用您的應用程序。無論如何,一般的可用性指導方針說你應該爲你的麪包屑使用類別而不是導航路徑(HTTP is stateless,歷史本身由瀏覽器保存)。 因此,一個動態的麪包屑已經沒有意義了,至少如果你使用不同的網址作爲你的觀點。