Richfaces and Primefaces have theme support, it is an attractive feature of the skin-able JSF components projects.
JSF 2.2 introduces a new feature named Resource Library Contracts which supports to apply different resources(css and js) and facelets template at runtime.
contracts resources files can be placed in /contracts folder under the web application root or /META-INF/contracts on classpath.
An example of contracts resources file structure in a web application.
/contracts /default /css defautl.css cssLayout.css template.xhtml /alternative /css defautl.css cssLayout.css template.xhtml
There are two contracts defined in the project, default and alternative.
The following is the content of /contracts/default/template.xhtml.
Facelets TemplateTopContent
The content of /contracts/alternative/template.xhtml is similar, only the css reference path is changed.
Facelets TemplateTopContent
In your facelets template file, you can use the contracts template directly. NOTE: The template path is /template.xhtml.
Theme Switcher
Sample of applying alternative.
In JSF 2.2, a new attribute contracts was added to f:view which can specify the specified contracts name, default and alternative in this project.
You can switch to the contracts dynamically through a backend bean.
Theme Switcher
Current Theme:#{themeSwitcher.theme}
In the template file, use two h:commandButton buttons to switch the contracts dynamically.
@Named @SessionScoped public class ThemeSwitcher implements Serializable { @Inject transient Instance log; private String theme = "default"; public void changeTheme( String _theme){ log.get().log(Level.INFO, "call changeTheme{0}", _theme); switch (_theme) { case "alternative": this.theme = "alternative"; break; default: this.theme = "default"; break; } } public String getTheme() { return theme; } public void setTheme(String theme) { this.theme = theme; } }
You can also configure the contracts in faces-config.xml file.
/themed-alt/* alternative /themed-default/* default
The /themed-alt will use the alternative and /themed-default will use default contracts.
Unfortunately, JSF 2.2 does not support EL as the value of contracts in faces-config.xml.
/themed-dyn/* #{themeSwitcher.theme}
This could be supported in a future version.
NOTE: In order to demonstrate the usage of Resources Library Contracts, I only changed the background color style in the css file. In the real world application, it could be much difference. For example, you use different css and layout for before and after login case.
Check out the complete codes from my github.com, and play it yourself.
https://github.com/hantsy/ee7-sandbox