Thursday, January 4, 2007

Dynamic JSF subviews

Dynamically switch between subviews in one main page

The easiest way would be the following:

<jsp:include page="#{myBean.includePage}" />

But this only works in JSF 1.2 + JSP 2.1 or newer. Unified Expression Language (the expressions starting with #) namely made its way from JSF to JSP in JSP 2.1. In older versioned environments the above snippet is not valid. To have JSP 2.1, you need a Servlet 2.5 compatible servletcontainer and a web.xml which is declared as per Servlet 2.5 specification.

The JSP 2.0 trick

If you're still using the old JSF 1.1 + JSP 2.0 (Servlet 2.4), then it's good to know that you can also access JSF managed beans using the old JSP EL notation ${managedBeanName}! You only have to keep in mind that this doesn't precreate the managed bean automatically when this line is called for the first time. So somewhere in the code before this line you should already have called the managed bean by JSF EL. The following example will work:

<h:panelGroup rendered="#{myBean.includePage != null}">
    <jsp:include page="${myBean.includePage}" />
</h:panelGroup>

Take care: do not use f:subview instead of h:panelGroup. Every include page should have its own f:subview with an unique ID.

The relevant java code of the backing bean MyBean.java should look like:

public String getIncludePage() {
    if (...) { // Do your thing, this is just a basic example with a nasty if-else tree.
        return "include1.jsp";
    } else if (...) {
        return "include2.jsp";
    } else if (...) {
        return "include3.jsp";
    } else {
        return "default.jsp";
    }
}

Copyright - There is no copyright on the code. You can copy, change and distribute it freely. Just mentioning this site should be fair.

(C) January 2007, BalusC