开发者

validation before rendering page [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

I'm new to JSF and using JSF2 to build a webapp which has several pages. I'm using a session scoped bean to keep some parameters that were set by going through the different pages.

When the session times out (or I redeploy the app) and I go to a specific page then this page is not able to render correctly because some data is missing from the session. At this point I want the home page to 开发者_开发问答be shown.

I want to use this mechanism for all pages. So in general I want to do some validation before rendering a page and direct the user to the home page if the validation fails.

How should I handle this?


In this particular case I'd use a simple filter which hooks on JSF requests and checks the presence of the managed bean in the session. The below example assumes the following:

  • FacesServlet is definied in web.xml as <servlet-name>facesServlet</servlet-name>
  • Your session scoped bean has a managed bean name of yourSessionBean.
  • Your home page is located at 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.
}

Or if you want to do it more JSF-ish, add a <f:event type="preRenderView"> to the master template.

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

with

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜