How to create a modular JSF 2.0 application?

I understand that your question basically boils down to How can I include Facelets views in a JAR?

You can do this by placing a custom ResourceResolver in the JAR.

public class FaceletsResourceResolver extends ResourceResolver {

    private ResourceResolver parent;
    private String basePath;

    public FaceletsResourceResolver(ResourceResolver parent) {
        this.parent = parent;
        this.basePath = "/META-INF/resources"; // TODO: Make configureable?
    }

    @Override
    public URL resolveUrl(String path) {
        URL url = parent.resolveUrl(path); // Resolves from WAR.

        if (url == null) {
            url = getClass().getResource(basePath + path); // Resolves from JAR.
        }

        return url;
    }

}

Configure this in webapp’s web.xml as follows:

<context-param>
    <param-name>javax.faces.FACELETS_RESOURCE_RESOLVER</param-name>
    <param-value>com.example.FaceletsResourceResolver</param-value>
</context-param>

Imagine that you’ve a /META-INF/resources/foo/bar.xhtml in random.jar, then you can just include it the usual way

<ui:include src="/foo/bar.xhtml" />

or even dynamically

<ui:include src="#{bean.path}" />

Note: since Servlet 3.0 and newer JBoss/JSF 2.0 versions, the whole ResourceResolver approach is not necessary if you keep the files in /META-INF/resources folder. The above ResourceResolver is only mandatory in Servlet 2.5 or older JBoss/JSF versions because they’ve bugs in META-INF resource resolving.

See also:

Leave a Comment