跳至主要内容

JSF 2.2: Theme

JSF 2.2: Theme

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.

Using contracts in a web application

The following is an example of contracts resources 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.
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
      xmlns:h="http://xmlns.jcp.org/jsf/html">
    
    <h:head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <link href="#{request.contextPath}/contracts/default/css/default.css" rel="stylesheet" type="text/css" />
        <link href="#{request.contextPath}/contracts/default/css/cssLayout.css" rel="stylesheet" type="text/css" />
        <title>Facelets Template</title>
    </h:head>
    
    <h:body>
        
        <div id="top" class="top">
            <ui:insert name="top">Top</ui:insert>
        </div>
        
        <div id="content" class="center_content">
            <ui:insert name="content">Content</ui:insert>
        </div>
        
    </h:body>
    
</html>
The content of /contracts/alternative/template.xhtml is similar, only the css reference path is changed.
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
      xmlns:h="http://xmlns.jcp.org/jsf/html">
    
    <h:head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <link href="#{request.contextPath}/contracts/alternative/css/default.css" rel="stylesheet" type="text/css" />
        <link href="#{request.contextPath}/contracts/alternative/css/cssLayout.css" rel="stylesheet" type="text/css" />
        <title>Facelets Template</title>
    </h:head>
    
    <h:body>
        
        <div id="top" class="top">
            <ui:insert name="top">Top</ui:insert>
        </div>
        
        <div id="content" class="center_content">
            <ui:insert name="content">Content</ui:insert>
        </div>
        
    </h:body>
    
</html>
In your facelets base template, you can use the contracts template directly.
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html" 
      xmlns:f="http://xmlns.jcp.org/jsf/core"
      xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
        <f:view contracts="alternative">
            <ui:composition template="/template.xhtml"

                <ui:define name="content">    
                    <h1>Theme Switcher</h1>
                    <p>Sample of applying alternative.</p>
                </ui:define>
            </ui:composition>
        </f:view>
</ui:composition>
A new attribute contracts is added to f:view in JSF 2.2, which can specify the contracts name you will use, here the options are default and alternative.
NOTE: The template path is /template.xhtml, and there is no any contract prefix needed.
You can switch between different contracts dynamically through a backend bean.
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html" 
      xmlns:f="http://xmlns.jcp.org/jsf/core"
      xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
        <f:view contracts="#{themeSwitcher.theme}">
            <ui:composition template="/template.xhtml">
                <ui:define name="content">    
                    <h1>Theme Switcher</h1>
                    <p>Current Theme:#{themeSwitcher.theme}</p>
                    <h:form>
                        <h:commandButton value="Default Theme" action="#{themeSwitcher.changeTheme('default')}">
                        </h:commandButton>    
                        <h:commandButton value="Alternative Theme" action="#{themeSwitcher.changeTheme('alternative')}">
                        </h:commandButton>    
                    </h:form>
                </ui:define>
            </ui:composition>
        </f:view>
</ui:composition>
In the template file, use two h:commandButton buttons to switch the contracts dynamically.
@Named
@SessionScoped
public class ThemeSwitcher implements Serializable {

    @Inject
    transient Instance<Logger> 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.
<application>
        <resource-library-contracts>
            <contract-mapping>
                <url-pattern>/themed-alt/*</url-pattern>
                <contracts>alternative</contracts>
            </contract-mapping>
            <contract-mapping>
                <url-pattern>/themed-default/*</url-pattern>
                <contracts>default</contracts>
            </contract-mapping>
        </resource-library-contracts>
</application>   
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.
<contract-mapping>
    <url-pattern>/themed-dyn/*</url-pattern>
    <contracts>#{themeSwitcher.theme}</contracts>
</contract-mapping>
This feature is motioned in jdevelopment.nl website, and could be supported in a future version.

Building a contracts jar

Packaging the resources library contracts files into a jar file is easy to share the contracts among various projects.
Move the contracts resources into a standalone Maven module, and refactor the above war project into three Maven modules.
theme-library
    /theme-client
    /theme-resources
theme-library is a parent POM module, includes two sub modules, theme-client and theme-resources.
theme-resources is a jar module, including all resources library contracts files.
theme-resources
    /src
        /main
            /resoruces
                /META-INF
                    /contracts
                        /default
                            /css
                            template.xhtml
                            javax.faces.contract.xml
                        /alternative
                            /css
                            template.xhtml
                            javax.faces.contract.xml
javax.faces.contract.xml is an empty marker file, which is required to identify resource library contracts in a jar file.
theme-client is a war project, which will apply the contracts defined in theme-resources module. Include theme-resources as a Maven dependency in the pom.xml of theme-client.
<dependency>
            <groupId>com.hantsylabs.example.ee7</groupId>
            <artifactId>jsf-theme-resources</artifactId>
            <version>1.0-SNAPSHOT</version>
</dependency>
NOTE: In the Glassfish 4(Mojarra is upgraded to 2.2.1), I have tried package the contracts files with and without an empty javax.faces.contract.xml. If packaging them without the empty javax.faces.contract.xml marker file, the predefined contracts can not be recognized when applying the contract rule in faces-config.xml, but they can be used in Themeswitcher backend bean. It looks a little weird.

Sample codes

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 can use different css and template layout before and after user is logged in.
Check out the complete codes from my github.com, and play it yourself.
https://github.com/hantsy/ee7-sandbox

评论

此博客中的热门博文

Create a restful application with AngularJS and Zend 2 framework

Create a restful application with AngularJS and Zend 2 framework This example application uses AngularJS/Bootstrap as frontend and Zend2 Framework as REST API producer. The backend code This backend code reuses the database scheme and codes of the official Zend Tutorial, and REST API support is also from the Zend community. Getting Started with Zend Framework 2 Getting Started with REST and Zend Framework 2 Zend2 provides a   AbstractRestfulController   for RESR API producing. class AlbumController extends AbstractRestfulController { public function getList() { $results = $this->getAlbumTable()->fetchAll(); $data = array(); foreach ($results as $result) { $data[] = $result; } return new JsonModel(array( 'data' => $data) ); } public function get($id) { $album = $this->getAlbumTable()->getAlbum($id); return new JsonModel(array("data" =>

JPA 2.1: Attribute Converter

JPA 2.1: Attribute Converter If you are using Hibernate, and want a customized type is supported in your Entity class, you could have to write a custom Hibernate Type. JPA 2.1 brings a new feature named attribute converter, which can help you convert your custom class type to JPA supported type. Create an Entity Reuse the   Post   entity class as example. @Entity @Table(name="POSTS") public class Post implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="ID") private Long id; @Column(name="TITLE") private String title; @Column(name="BODY") private String body; @Temporal(javax.persistence.TemporalType.DATE) @Column(name="CREATED") private Date created; @Column(name="TAGS") private List<String> tags=new ArrayList<>(); } Create an attribute convert

Auditing with Hibernate Envers

Auditing with Hibernate Envers The approaches provided in JPA lifecyle hook and Spring Data auditing only track the creation and last modification info of an Entity, but all the modification history are not tracked. Hibernate Envers fills the blank table. Since Hibernate 3.5, Envers is part of Hibernate core project. Configuration Configure Hibernate Envers in your project is very simple, just need to add   hibernate-envers   as project dependency. <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-envers</artifactId> </dependency> Done. No need extra Event listeners configuration as the early version. Basic Usage Hibernate Envers provides a simple   @Audited   annotation, you can place it on an Entity class or property of an Entity. @Audited private String description; If   @Audited   annotation is placed on a property, this property can be tracked. @Entity @Audited public class Signup implements Serializa