2013-04-13 44 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