Thursday, April 30, 2009

Multiple Faces-Config.xml in your JSF application.

Modular JSF code.

Facelets are a great templating tool for JSF and can also give performance benefits when you properly structure the way you load the pages.

If you want to modularize your web application by packing the backing beans in separate jar files, the JSF specification allows you to do that. All you have to do is pack the beans in a separate jar

file and in the META-INF folder you put your faces-config.xml file. According to the JSF specification all the jar files that contain a faces-config.xml are also automatically loaded.

You can also pack the jsp files that are specific to the module in the same jar. The trick you define a custom class that implements "com.sun.facelets.impl.ResourceResolver" interface and in your web.xml file add the facelet parameter to tell your web app to use the new custom resource resolver.


<code>
<context-param>
<param-name>facelets.RESOURCE_RESOLVER</param-name>
<param-value>my.very.small.company.CustomResourceResolver</param-value>
</context-param>
</code>


The resource resolver has one single method to implement and here is a snapshot of that code.


<code>
public URL resolveUrl(String path) {
try {
if(null != path && path.contains("/CUSTOM_INCLUDE/")){
path = path.substring(path.indexOf("/CUSTOM_INCLUDE/") + 20);
URL url = THISCLASS.class.getClassLoader().getResource(path);
return url;
}
// Default ResourceResolver
return Resource.getResourceUrl(FacesContext.getCurrentInstance(), path);
} catch (IOException e) {
throw new FacesException(e);
}
}
</code>


Though this mechanism works for the jsp pages and the java files as separate sub modules, if the code depends on CSS or java script then that does not get included properly. A new framework is available on java.net called "weblets" that looks much better than the above approach.

No comments:

Post a Comment