【问题标题】:validation before rendering page [closed]渲染页面前的验证[关闭]
【发布时间】:2011-06-17 10:15:29
【问题描述】:

我是 JSF 的新手,我使用 JSF2 构建了一个包含多个页面的 webapp。我正在使用会话范围的 bean 来保留一些通过不同页面设置的参数。

当会话超时(或我重新部署应用程序)并转到特定页面时,该页面无法正确呈现,因为会话中缺少某些数据。此时我希望显示主页。

我想对所有页面使用这种机制。所以一般来说,我想在渲染页面之前做一些验证,如果验证失败,将用户引导到主页。

我应该如何处理?

【问题讨论】:

  • 类似问题(及答案)here
  • 在我的用例中,会话超时意味着我的会话 bean 中的数据不再可用。这就是我想要通过将用户引导到不同页面来响应的内容。当我收到 ViewExpiredException 时,我也遇到了问题,但这是一个不同的问题。

标签: jsf-2


【解决方案1】:

在这种特殊情况下,我将使用一个简单的filter,它挂钩 JSF 请求并检查会话中托管 bean 的存在。下面的例子假设如下:

  • FacesServletweb.xml 中定义为 <servlet-name>facesServlet</servlet-name>
  • 您的会话范围 bean 的托管 bean 名称为 yourSessionBean
  • 您的主页位于home.xhtml

@WebFilter(servletName="facesServlet")
public class FacesSessionFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession(false);

        if (!request.getRequestURI().endsWith("/home.xhtml") && (session == null || session.getAttribute("yourSessionBean") == null)) {
            response.sendRedirect(request.getContextPath() + "/home.xhtml"); // Redirect to home page.
        } else {
            chain.doFilter(req, res); // Bean is present in session, so just continue request.
        }
    }

    // Add/generate init() and destroy() with empty bodies.
}

或者,如果您想做更多 JSF 风格,请将 <f:event type="preRenderView"> 添加到主模板。

<f:metadata>
    <f:event type="preRenderView" listener="#{someBean.preRenderView}" />
</f:metadata>

@ManagedProperty(value="#{yourSessionBean}")
private YourSessionBean yourSessionBean;

public void preRenderView() {
    if (yourSessionBean.isEmpty()) {
        yourSessionBean.addPage("home");
        FacesContext.getCurrentInstance().getExternalContext().redirect("/home.xhtml");
    }
}

【讨论】:

  • thanx BalusC.我确实更喜欢 JSF-ish 解决方案。我试过了,但是当会话 bean 为空时,它会进入一个永无止境的循环。所以我可能只在我不在主页上时才需要重定向(就像你的第一个解决方案一样)。我会按照你描述的方式试试这个。
  • 有道理。您想以某种方式更改会话 bean,以便在重定向后条件评估为 false。我编辑了答案。您还可以在与 home.xhtml 关联的托管 bean 的 @PostConctruct 中完成这项工作。
  • 你的意思是 yourSessionBean.addPage("home") 使 yourSessionBean.isEmpty() 返回 false?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-11
  • 2018-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多