2013-04-13 51 views
0

我做了一些研究,如何做到這一點,我發現了一些孤立的解決方案,但我無法弄清楚,如何將它們和什麼方式被認爲是最佳實踐。我正在使用tomcat和jsf 2.x.JSF 2.x中的ExceptionHandling,從另一個訪問SessionScoped託管bean並重定向

場景: 我有一個會話scoped bean,mycontrollerA。控制器涉及到myviewa.xhtml。在viewA上觸發commandLink後,觸發了mycontrollerA.doThis()動作。在這個方法中,我想使用try-catch,如果發生異常,我想重定向到異常報告視圖'exception.xhtml'。相關的控制器ExceptionController有一個屬性'message',我想在myControllerA中設置相應的值。

問題:如果我嘗試抓取我的exceptionController bean,則出現錯誤。我想,這只是不存在,因爲它從來沒有被初始化。我希望有一種通用的方法可以從另一個SessionScoped bean中獲取SessionScoped bean,這個bean可以在開箱即用的情況下處理這個「必要時創建」。此外,我認爲我的重定向代碼可以改進。

在此先感謝。

public String doThis() { 
    try { 
     throw new RuntimeException("TestExc"); 
} catch (RuntimeException e) { 
    //ExceptionController exceptionController = (ExceptionController) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("exceptionController"); 
    //exceptionController.setMessage("Fehlerinfo: " + e.getMessage()); 
    try { 
     FacesContext.getCurrentInstance().getExternalContext().redirect("exception.xhtml"); 
     } catch (IOException e1) { 
      e1.printStackTrace(); 
     } 
    } 
    return null; 
} 

@ManagedBean(name = "exceptionController") 
@SessionScoped 
public class ExceptionController { ... } 
+0

首先,這個'mycontrollerA' bean是否有任何特殊的原因是'@SessionScoped'?我問這是因爲它看起來是將它與特定的視圖鏈接起來的,所以使用'@ ViewScoped'註釋會更方便。話雖如此,您可以使用'@ ManagedProperty'註釋引用來自'@ ViewScoped'的'@ SessionScoped' bean。但請記住,除非你這樣做,否則這個bean不會被初始化。 –

回答

1

你可以嘗試通過ELResolver解決這個bean:

FacesContext fc = FacesContext.getCurrentInstance(); 
ELContext el = fc.getELContext(); 
ExceptionController exCtrl = (ExceptionController) el.getELResolver() 
    .getValue(el, null, "exceptionController"); 

你的問題可能是,該bean不是之前創建的,因此尚未在會話中。使用ELResolver方法應該創建它。

+0

非常感謝Michi,它正在工作! – Jochen