【问题标题】:Redirect in session bean @PostConstruct在会话 bean 中重定向 @PostConstruct
【发布时间】:2013-10-10 19:47:07
【问题描述】:

我有一个 JSF 2.0 应用程序,它有一个从 home.xhtml 访问的会话 bean,如下所示:

@Named(value = "home")
@SessionScoped
public class Home implements Serializable{

@PostConstruct
    public void init() {
// Retrieve database data here
        try {
        } catch (Exception ex) {
            System.out.println("EXCEPTION");


        }
    }
}

我想做的是,如果数据库检索失败,重定向到error.xhtml页面。上面的init方法是怎么做到的?

【问题讨论】:

    标签: jsf redirect


    【解决方案1】:

    您可以使用External Context's redirect(java.lang.String) 方法。

    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    externalContext.redirect("page2.xhtml");
    

    【讨论】:

      【解决方案2】:

      无需手动处理重定向。直接抛出异常即可。

      @PostConstruct
      puclic void init() throws Exception { // Please be more specific, e.g. SQLException.
          // Retrieve database data here without try/catch block.
      }
      

      它最终会出现在 HTTP 500 错误页面中,其位置(以及外观)可以由 web.xml 自定义:

      <error-page>
          <error-code>500</error-code>
          <location>/WEB-INF/errorpages/500.xhtml</location>
      </error-page>
      

      如果您还想讨论 ajax 请求的异常,请查看以下答案:What is the correct way to deal with JSF 2.0 exceptions for AJAXified components?

      【讨论】:

      • @onepotato:停止陈述假设。提出问题并陈述观察结果。
      • 我一定会在以后的互动中注意到这一点。
      • 嗨@BalusC,如果用户名或密码错误,我可以使用相同的方法重定向回登录页面吗?还是有其他更可接受​​的方式来执行此操作?
      猜你喜欢
      • 1970-01-01
      • 2011-12-23
      • 2012-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-09
      相关资源
      最近更新 更多