2015-05-26 67 views
0

我們在頁面中存在動態菜單項,並在數據庫中存儲了include-source .xhtml的鏈接,在這種情況下,如果源xhtml輸入錯誤或未能找到它引發的應用程序上下文TagAttributeException與無效的路徑消息。處理TagAttributeException並更改ui:includeSrc

在此事件發生後,如果我們發出任何ajax請求失敗,原因是在恢復視圖階段嘗試使用無效的xhtml(包括src)進行恢復。

有什麼辦法可以在運行時處理這個異常,並將xhtml src改爲默認的xhtml。這樣任何進一步的AJAX調用都可以工作。

XHTML

<h:form prependId="false">    

      <p:commandButton actionListener="#{exceptionPF.includePage()}" 
       ajax="true" 
       value="Include Wrong Source" /> 

      <p:commandButton actionListener="#{exceptionPF.includeRightPage()}" 
       ajax="true" 
       value="Include Right Source" /> 

      <p:panel id="div1" > 

       <ui:include src="#{exceptionPF.srcPage}" /> 

      </p:panel>   


     <p:ajaxExceptionHandler type="javax.faces.view.facelets.TagAttributeException" 
         update="exceptionDialog" 
         onexception="PF('exceptionDialog').show();" /> 



     <p:dialog id="exceptionDialog" header="Exception '#{pfExceptionHandler.type}' occured!" widgetVar="exceptionDialog" 
      height="500px"> 
    Message: #{pfExceptionHandler.message} <br/> 
    Stack-Trace: <h:outputText value="#{pfExceptionHandler.formattedStackTrace}" escape="false" /> <br /> 

    <p:button onclick="document.location.href = document.location.href;" 
       value="Reload!" 
       rendered="#{pfExceptionHandler.type == 'javax.faces.application.ViewExpiredException'}" /> 
</p:dialog> 


    </h:form> 

@Named 
@ViewScoped 
public class ExceptionPF implements Serializable { 

String srcPage; 

public String getSrcPage() { 
    return srcPage; 
} 

public void setSrcPage(String srcPage) { 
    this.srcPage = srcPage; 
} 

public void includePage() 
{ 
    setSrcPage("wrong.xhtml"); 
    RequestContext.getCurrentInstance().update("div1"); 
} 

public void includeRightPage() 
{ 
    setSrcPage("correct.xhtml"); 
    RequestContext.getCurrentInstance().update("div1"); 
} 

}

錯誤

19:38:08,978 INFO [stdout] (default task-14) *****BEFORE **** RESTORE_VIEW 
    19:38:08,985 INFO [stdout] (default task-14) *****AFTER **** RESTORE_VIEW 
    19:38:08,986 SEVERE [javax.enterprise.resource.webcontainer.jsf.context]  
    (default task-14) javax.faces.view.facelets.TagAttributeException: 
    /index.xhtml @33,62 
    <ui:include src="#{exceptionPF.srcPage}"> Invalid path : wrong.xhtml 
     at com.sun.faces.facelets.tag.ui.IncludeHandler.apply(IncludeHandler.jav 

回答

1

當視圖本身導致異常時,無法從視圖方面處理異常。

您可以使用ViewDeclarationLanguage#viewExists()來檢查給定視圖是否存在。您應該在設置srcPage之前執行此操作,並在必要時在單獨的(布爾型)變量中保留錯誤的值。

這裏是你如何能在一個實用程序方法的味道使用它:

public static boolean viewExists(String viewId) { 
    FacesContext context = FacesContext.getCurrentInstance(); 
    return context.getApplication().getViewHandler() 
     .getViewDeclarationLanguage(context, viewId).viewExists(context, viewId); 
} 
+0

感謝您的解決方案,它解決了我們的情況。 – Balaji

+0

不客氣。 – BalusC